亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用jQueryAjax將對象列表傳遞給MVC控制器方法

使用jQueryAjax將對象列表傳遞給MVC控制器方法

縹緲止盈 2019-07-25 12:14:25
使用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個贊

使用NickW的建議,我可以用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; }}

我從中學到了兩件事:

  1. 在Ajax()函數中,contentType和dataType設置是絕對必要的。如果他們失蹤了就沒用了。經過多次反復試驗,我發現了這一點。

  2. 要將對象數組傳遞給MVC控制器方法,只需使用JSON.strgify({‘Things’:Things})格式即可。

我希望這能幫到別人!




查看完整回答
反對 回復 2019-07-27
?
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...}



查看完整回答
反對 回復 2019-07-27
  • 2 回答
  • 0 關注
  • 345 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號