Good evening, guys! I've got an odd one.
Long story short, I'm sending a post from a java script client-side to get an integer back from my C# Controller, but the response.data is coming back null. The twist is that both the C# method and the javascript/jquery function are literally copied and pasted from another project where both of them work. The project they're taken from is a VS2010 project, and they're pasted into a VS2012 project. I'm not sure if this is the issue, but it could be related. The integer is fetched correctly in the C# and none of the information is missing. Even more mysteriously, the success message is coming back correctly to the response object client-side. However the response.data object is null, and throws an exception.
Any and all help is very much appreciated. Thanks!
This is the method in the C#:
[HttpPost]
public JsonResult GetMaxFileSize()
{
int MaxFileSize = 0;
// Get max file size.
string MaxPatientFileSizeInMegsString = System.Web.Configuration.WebConfigurationManager.AppSettings["MaxFacilityLogoFileSizeInMegs"];
MaxFileSize = int.Parse(MaxPatientFileSizeInMegsString);
return Json(new AjaxResponse(true, "Success.", new { maxFileSize = MaxFileSize }));
}
And this is the javascript/jquery function:
function getMaxFileSize() {
$.post(settings.actions.getMaxFileSize, function (response) {
var maxFileSize = 0;
// Assign the correct size to the hidden field.
if (response.success) {
maxFileSize = response.data.maxFileSize;
$(settings.selectors.maxFileSizeHiddenInput).val(maxFileSize);
}
// Assign 0 to max file size: user cannot upload files.
else {
$(settings.selectors.maxFileSizeHiddenInput).val(maxFileSize);
}
});
}
Works fine here!
TestController.cs
public class AjaxResponse
{
public AjaxResponse(bool success, object data)
{
this.success = success;
this.data = data;
}
public bool success { get; set; }
public object data { get; set; }
}
[HttpPost]
public ActionResult Ajax()
{
return Json(new AjaxResponse(true, new { num = 5 }));
}
Index.cshtml
$.post('@Url.Action("Ajax", "Test")', function (response) {
var num = 0;
debugger;
// Assign the correct size to the hidden field.
if (response.success) {
num = response.data.num;
$('h2').html(num);
}
// Assign 0 to max file size: user cannot upload files.
else {
$('h2').html(num);
}
});
JSON response in FireBug:
{"success":true,"data":{"num":5}}