猿问

Ajax 对象数组到方法

我一直在尝试将这个数组ajax 到我的控制器,但是当它到达时数据被设置为空。


我的功能:


function saveChanges() {

var grid = $("#GridName").data("kendoGrid");

var gridData = grid.dataSource.data();


var dataArray = [];


for (var i = 0; i < gridData.length; i++) {

    dataArray.push({Date: gridData[i].Date, Name: gridData[i].ProductName});

}


$.ajax({

    url: GetUrlRoot() + "Controller/Method",

    data: { gridData: dataArray },

    async: false,

    success: function () {


    },

    error: function () {


    },

    cache: false,

})


grid.saveChanges();

}

我的控制器:


public virtual string Method(List<DateName> gridData)

    {



        return string.Empty;

    }


public class DateName

{

    public DateTime Date { get; set; }

    public string Name { get; set; }

}

控制器识别出已发送 1 条记录,但该记录的值为空。


慕盖茨4494581
浏览 196回答 3
3回答

喵喔喔

&nbsp;data: { gridData: dataArray },在java脚本中将匹配c#中的以下对象模型public class GridDataObject {&nbsp; &nbsp; public List<DateName> gridData { get; set; }}但是,这与中的参数参数不匹配public virtual string Method(List<DateName> gridData)因此,首先,更新控制器操作以期望从客户端发送所需的对象模型。一个简单的例子在控制器中看起来像这样[HttpPost]public virtual string Method(GridDataObject data) {&nbsp; &nbsp; //...&nbsp; &nbsp; var gridData = data.gridData;&nbsp; &nbsp; //...&nbsp; &nbsp; return string.Empty; //strictly for demo purposes.&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;}其次,客户端需要使用正确的格式发送数据。//...var url = GetUrlRoot() + "Controller/Method";var data&nbsp; = { gridData: dataArray };$.ajax({&nbsp; &nbsp; url: url,&nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; data: data,&nbsp; &nbsp; async: false,&nbsp; &nbsp; success: function () {&nbsp; &nbsp; }&nbsp; &nbsp; error: function () {&nbsp; &nbsp; },&nbsp; &nbsp; cache: false,});

阿晨1998

使用dataType: "json"和traditional: true$.ajax({&nbsp; &nbsp; url: GetUrlRoot() + "Controller/Method",&nbsp; &nbsp; data: dataArray,&nbsp; &nbsp; async: false,&nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; traditional: true,&nbsp; &nbsp; success: function () {&nbsp; &nbsp; },&nbsp; &nbsp; error: function () {&nbsp; &nbsp; },&nbsp; &nbsp; cache: false,})

慕码人2483693

在您的 jQuery Ajax 部分:将设置数据更改为:data: JSON.stringify(dataArray),method: 'POST', //or type:'POST' based on jQuery version...然后您还可以将控制器更改为:public virtual string Method([FromBody]DateName[] gridData){...}因此,通过这些更改,$.ajax 会将 JSON 发布到您的控制器,并且您的控制器将从请求正文中解析 JSON。
随时随地看视频慕课网APP
我要回答