简体   繁体   English

如何映射具有列表属性的 Mvc 视图模型和 ajax 发布数据?

[英]How to map Mvc View model and ajax post data which have list property?

I have a MVC controller action with inputModel parameter which have list type property and , I ,m using $('form').serialize() to serialize the form content and append some of my custom data to serialized string, but inside the action method input model object the list property is empty, Can any one help me , below is the code samples我有一个带有 inputModel 参数的 MVC 控制器操作,它具有列表类型属性,并且我使用$('form').serialize()来序列化表单内容并将我的一些自定义数据附加到序列化字符串中,但在操作内部方法输入模型对象列表属性为空,谁能帮帮我,下面是代码示例

My controller我的控制器

[HttpPost]
public ActionResult Edit(ALDS.Web.Areas.Direct2M3.Models.ItemInputModel collection)
{   }

ItemInputModel class ItemInputModel 类

 public class ItemInputModel
    {
        //......Some property here..
        public List<FabricCompositionInputModel> FabricCompositions { get; set; }
    }

FabricCompositionInputModel class FabricCompositionInputModel 类

 public class FabricCompositionInputModel
    {
        public int ItemID { get; set; }
        public string CompositionCode { get; set; }
        public decimal Value { get; set; }

    }

Ajax call Ajax 调用

function save() {

    var compositionData = generateCompositionForSave(); //Returns array
    var data = $('form').serialize();
    var d2 = JSON.stringify(compositionData);

    var data2 = data + '&FabricCompositions=' + d2;

    $.ajax({
        type: 'POST',
        dataType: 'json' ,
        cache: false,
        url: '/ItemMaster/Edit',
        data: data2,
        success: function (data, textStatus, jqXHR) {
            sucess(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            failed(jqXHR);
        }

    });

}

Array generating function数组生成函数

function generateCompositionForSave() {
    var arr = [];
    var delClassList = $('#compositionContainer').find('.btnRemoveCompositions');
    for (var c = 0; c < delClassList.length; c++) {
        var row = $(delClassList[c]).closest('.row');
        var code = row.find('.compositionCode').val();
        var value = parseInt(row.find('.compositionValue').val());
        arr.push({ItemID:0, CompositionCode:code, Value:value});
    }

    return arr;
}

Your not building the data correctly, and it needs to be你没有正确构建数据,它需要

var compositionData = generateCompositionForSave();
var data = $('form').serializeObject(); // see function below
data['FabricCompositions'] = compositionData; // add the array to the serialized data
var data2 = JSON.stringify({ collection: data }), // stringify it

$.ajax({
    type: 'POST',
    contentType: "application/json; charset=utf-8", // add contentType
    dataType: 'json' ,
    cache: false,
    url: '@Url.Action("Edit", "ItemMaster")', // don't hard code your url's
    data: data2,
    success: function (data, textStatus, jqXHR) {
        ....

And add the following function (warning: this will not work correctly for a <select multiple> element)并添加以下功能(警告:这对于<select multiple>元素将无法正常工作)

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] === undefined) {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

Note that if you generate your form controls correctly using a for loop or custom EditorTemplate for typeof FabricCompositionInputModel (refer Post an HTML Table to ADO.NET DataTable ), for example请注意,如果您使用for循环或自定义EditorTemplate for typeof FabricCompositionInputModel正确生成表单控件(请参阅Post an HTML Table to ADO.NET DataTable ),例如

for(int i = 0; i < Model.FabricCompositions.Count; i++)
{
    @Html.TextBoxFor(m => m.FabricCompositions[i].CompositionCode)
    @Html.TextBoxFor(m => m.FabricCompositions[i].Value)
}

then all that is required is那么所需要的就是

var data = $('form').serialize();
$.ajax({
    type: 'POST',
    dataType: 'json' ,
    cache: false,
    url: '@Url.Action("Edit", "ItemMaster")',
    data: data,
    success: function (data, textStatus, jqXHR) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM