2017-09-13 123 views
0

如何使用由C#中的AJAX請求發送的Json格式的數據?將Json數據映射到使用AJAX和C#的對象#

下面是用jQuery和AJAX

<script type="text/javascript"> 
    $(function() { 
     $("#btnGet").click(function() { 
      var values = 
       { 
        "Name": "Manuel Andrade", 
        "DateOfBirth": "12/01/1995" 
       } 
      $.ajax({ 
       type: "POST", 
       url: "/api/WebApi/GetAge", 
       data: values, 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: function (response) { 
        alert("Hello: " + response.Name + ".\nCurrent Date and Time: " + response.DateTime); 
       }, 
       failure: function (response) { 
        alert(response.responseText); 
       }, 
       error: function (response) { 
        alert(response.responseText); 
       } 
      }); 
     }); 
    }); 
</script> 

查看這裏的控制器:

public class PersonController : ApiController 
{ 
    [System.Web.Http.Route("api/WebApi/GetAge")] 
    [System.Web.Http.HttpPost] 
    public Person GetAge(Person person) 
    { 
     //person = new Person(); 
     //person.Name = "Luis"; 

     JsonTest(person); 


     //int ageInMonths = calculateAgeInMonths(person); 
     //int ageInYears = calculateAgeInYears(person); 

     //System.Diagnostics.Debug.WriteLine(ageInMonths); 
     //System.Diagnostics.Debug.WriteLine(ageInYears); 

     return person; 
     } 
    } 

的角色模型具有完全相同的屬性在視圖中的Json變量。它不應該自動創建一個對象嗎? JsonTest()方法正常工作,它用於序列化數據。如果我取消對Luis的實例化和分配的註釋,那麼該方法確實會返回帶有該數據的Json到視圖。但是,如果我嘗試使用person參數就像它拋出一個空的異常。如何將View中的var值傳遞給GetAge方法,以便將其分配給對象?

+0

哪個框架和哪個版本是這樣的? –

回答

0

當我刪除contentType: "application/json; charset=utf-8",行時,它工作正常。

默認情況下,它不作爲application/json返回。