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);
}
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();
});
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.
You should add JsonBehavious if you are not getting values.
return Json(returnValue, JsonRequestBehavior.AllowGet);
Try this:
success: function (result) {alert(JSON.stringify(result)); }
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.
Try this piece of code :
return Json(returnValues, JsonRequestBehavior.AllowGet);