2014-02-14 54 views
0

晚上好,夥計們!我有一個奇怪的。Json數據返回null

長話短說,我從java腳本客戶端發送一個帖子來從我的C#控制器獲取一個整數,但response.data返回null。其實,C#方法和javascript/jquery函數都是從另一個項目中直接複製和粘貼的。他們從中獲得的項目是一個VS2010項目,它們被粘貼到一個VS2012項目中。我不確定這是否是問題,但可能是相關的。整數在C#中正確提取,並且沒有任何信息丟失。更神祕的是,成功消息正確地返回到響應對象客戶端。但是,response.data對象爲null,並引發異常。

任何和所有的幫助,非常感謝。謝謝!

這是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 })); 
    } 

這是JavaScript/jQuery函數:

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); 
      } 
     }); 
    } 

回答

0

做工精細這裏!

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); 
     } 
    }); 

在Firebug JSON響應:

{"success":true,"data":{"num":5}} 
+0

喜吉文。你的答案中的AjaxResponse類的結構給了我一個線索,它是什麼:我的應用程序中的AjaxResponse類(不是我自己構建的)沒有正確地分配數據(沒有使用'this',而且進來的參數是與對象屬性Data = Data相同的名稱和外殼)。基本上這總是保持數據爲空。謝謝你的幫助! –