2014-09-25 26 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