2014-09-25 31 views
0

我想尽一切办法在一个AJAX调用发送JSON和在行动接受它,(我用一个WebMethod尝试和有同样的问题)控制器,该行动得到了与json相同属性的模型。但是收到Action的变量总是空的。从阿贾克斯jQuery的JSON发送到接收模型

这里是代码: 型号:

public class Person 
    { 
     public string Name { get; set; } 
     public int Age { get; set; } 
    } 

操作:

public ActionResult InsertPerson(Person person) 
    { 

     return View(); 

    } 

最后认为:

<input id="btnSend" type="button" value="Send" /> 

<script type="text/javascript"> 
$(document).ready(function() { 
    var PersonDto = function (name, age) { 
     this.Name = name; 
     this.Age = age; 
    }; 

    var person1 = new PersonDto("Diego", 27); 


    $('#btnSend').on('click', function() { 
     $.ajax({ 
      cache: false, 
      url: '@Url.Action("InsertPerson", "JsonTest")', 
      type: "GET", 
      contentType: "application/x-www-form-urlencoded", 
      dataType: "text", 
      data: "{person:" + JSON.stringify(person1) + "}", 

      success: function (data) { 

       alert(data); 

      }, 
      error: function (xhr, status, error) { 
       alert(xhr); 
       displayJsonError(xhr); 
      } 
     }); 

    }); 

}); 


</script> 

所有我跟随节目这样的教程做到这一点,我检查了数据中的json,似乎没问题,我尝试在web方法中执行相同的操作它没有奏效,不知道我做错了什么。

回答

0

你应该能够简化并张贴只有数据为JSON。请特别注意type,contentType和data属性。

$.ajax({ 
     cache: false, 
     url: '@Url.Action("InsertPerson", "JsonTest")', 
     type: "POST", 
     contentType: "application/json", 
     data: JSON.stringify(person1), 
     success: function (data) { 
      alert(data); 
     }, 
     error: function (xhr, status, error) { 
      alert(xhr); 
      displayJsonError(xhr); 
     } 
    }); 
+0

错误是在contentType中和类型。数据以两种方式工作。为什么它必须是POST类型? – 2014-09-25 15:42:18

+0

使用POST将数据放在请求的主体中,而不是在url参数中。一般来说,当你发送数据到服务器时,你应该使用POST。 – 2014-09-25 15:44:36