使用jQueryAjax將對象列表傳遞給MVC控制器方法我試圖使用jQuery的Ajax()函數將一個對象數組傳遞給MVC控制器方法。當我進入PassThing()C#控制器方法時,參數“Things”為NULL。我嘗試過使用一種類型的List作為參數,但這也不起作用。我做錯什么了?<script type="text/javascript">
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Xhr/ThingController/PassThing',
data: JSON.stringify(things)
});
});</script>public class ThingController : Controller{
public void PassThing(Thing[] things)
{
// do stuff with things here...
}
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}}
2 回答
浮云間
TA貢獻1829條經驗 獲得超4個贊
things = JSON.stringify({ 'things': things });
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/PassThings',
data: things,
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
}); });public void PassThings(List<Thing> things){
var t = things;}public class Thing{
public int Id { get; set; }
public string Color { get; set; }}在Ajax()函數中,contentType和dataType設置是絕對必要的。如果他們失蹤了就沒用了。經過多次反復試驗,我發現了這一點。 要將對象數組傳遞給MVC控制器方法,只需使用JSON.strgify({‘Things’:Things})格式即可。
ABOUTYOU
TA貢獻1812條經驗 獲得超5個贊
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }];$.post('@Url.Action("PassThings")', { things: things },
function () {
$('#result').html('"PassThings()" successfully called.');
});[HttpPost]public void PassThings(IEnumerable<Thing> things){
// do stuff with things here...}- 2 回答
- 0 關注
- 345 瀏覽
添加回答
舉報
0/150
提交
取消
