2017-09-13 89 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返回。