使用jQueryAjax將對(duì)象列表傳遞給MVC控制器方法我試圖使用jQuery的Ajax()函數(shù)將一個(gè)對(duì)象數(shù)組傳遞給MVC控制器方法。當(dāng)我進(jìn)入PassThing()C#控制器方法時(shí),參數(shù)“Things”為NULL。我嘗試過(guò)使用一種類型的List作為參數(shù),但這也不起作用。我做錯(cuò)什么了?<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貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超4個(gè)贊
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()函數(shù)中,contentType和dataType設(shè)置是絕對(duì)必要的。如果他們失蹤了就沒(méi)用了。經(jīng)過(guò)多次反復(fù)試驗(yàn),我發(fā)現(xiàn)了這一點(diǎn)。 要將對(duì)象數(shù)組傳遞給MVC控制器方法,只需使用JSON.strgify({‘Things’:Things})格式即可。

ABOUTYOU
TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
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 關(guān)注
- 335 瀏覽
添加回答
舉報(bào)
0/150
提交
取消