将Json数据返回给Ajax调用 [英] Return Json data to Ajax call
问题描述
我在MVC中有一个方法发布到该方法,我需要将一些数据返回给处理. 这是我发布并返回的MVC方法,Value是json数据.
I have a method in MVC that I post to it and I need to return some data back to process. This is my MVC method that I post to and return Value is a json data.
[HttpPost]
public JsonResult GetCalculateAmortizationSchedule()
{
var data = ...
var httpClient = new HttpClient();
var response = httpClient.PostAsJsonAsync("http://localhost:62815/v1/APR/CalculateAmortizationSchedule", data).Result;
var returnValue = response.Content.ReadAsAsync<Dictionary<int, AmItem>>().Result;
return Json(returnValue);
}
这是我的AJax调用,已成功运行MVC方法.
This is my AJax call that successfully run the MVC method.
$('#MyForm').submit(function (e) {
debugger;
$.ajax({
url: "/home/GetCalculateAmortizationSchedule",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("success");
},
error: function (result) {
alert("error");
}
});
e.preventDefault();
});
我的问题是如何从方法中获取返回值?当我在返回Json(returnValue)之后运行此程序时,该值未返回Ajax方法,而不是看到成功警报,而是看到错误警报.
My problem is how to catch the return value from method? when I run this after return Json(returnValue) the value is not returning to Ajax method and instead of seeing the Success Alert I see the error Alert.
推荐答案
尝试一下:
success: function (result) {alert(JSON.stringify(result)); }
从您在下面的注释中发布的错误来看,字典无法序列化.尝试如其他答案中所述设置AllowGet
.如果不起作用,则需要将Dictionary转换为可序列化的其他对象.或者,您也可以按照此步骤在控制器中将Dictionary序列化为json.
From the error you have posted in comments below, it appears Dictionary is not serializable. Try setting AllowGet
as mentioned in other answers. If doesn't work, you will need to convert Dictionary to some other object that is serializable. Or you may follow this to serialize Dictionary to json in your controller.
这篇关于将Json数据返回给Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!