繁体   English   中英

使用ajax将对象发送到mvc控制器

[英]Send object to mvc controller using ajax

我在对象中传递多个参数,然后将其传递给控制器​​中的Method。 它正在击中该方法,但它没有携带从ajax调用发送到该方法的数据。 当我要检查模型的对象时,它显示为null。 我可以这样发送数据还是应该尝试其他方法? 在此先感谢请帮助我。 这是我的代码。

 var Color = [], Material = [], Size = [], FinishingType = [], Style = []; $('.productFilterLabelList .filterList').on('change', '[type=checkbox]', function () { debugger; var Main = {}; var filterType = $(this).parents('.productFilterLabelList').find('.hdn-filter-type').val(); var filterTypeID = $(this).val(); var ischeked = $(this).is(':checked'); if (ischeked) { if (filterType == 'color') { Color.push(filterTypeID); } else if (filterType == 'size') { Size.push(filterTypeID); } else if (filterType == 'finsih') { FinishingType.push(filterTypeID); } else if (filterType == 'material') { Material.push(filterTypeID) } else { Style.push(filterTypeID); } } else { alert('hello'); if (filterType == 'color') { Color.pop(filterTypeID); } else if (filterType == 'size') { Size.pop(filterTypeID); } else if (filterType == 'finsih') { FinishingType.pop(filterTypeID); } else if (filterType == 'material') { Material.pop(filterTypeID) } else { Style.pop(filterTypeID); } } Main = { Color: Color, Size: Size, FinishingType: FinishingType, Material: Material, Style: Style } console.log(Main); $.ajax({ url: '/Home/SearchByAllFilterTags', type: "Get", contentType: "application/json", dataType: "json", data: '{Main:' +JSON.stringify(Main)+' }', success: function (results) { } }) }); public ActionResult SearchByAllFilterTags(ProductFilterViewModel Main) { return Json("", JsonRequestBehavior.AllowGet); }`public class ProductFilterViewModel { public int[] Color { get; set; } public int[] Material { get; set; } public int[] Size { get; set; } public int[] FinishingType { get; set; } public int[] Style { get; set; } public int[] Pattern { get; set; } //public string FilterText { get; set; } //public List<ProductFilterViewModel> FilterTextList { get; set; } }` 

您不需要对对象进行字符串化。 只需传递您的Main对象:

$.ajax({
    url: '/Home/SearchByAllFilterTags',
    type: "Get",
    contentType: "application/json",
    dataType: "json",
    traditional: true,
    data: Main,
    success: function (results) {
    }
})

编辑:

如果您的数组在操作方法中为空,请尝试将traditional: true添加到ajax设置

你不需要字符串化。 使用以下格式:

 Main = {
            "Color": [{Color}],
            "Size": [{Size}],
            "FinishingType": [{FinishingType}],
            "Material": [{Material}],
            "Style": [{Style}]
        }
        console.log(Main);
        $.ajax({
            url: '/Home/SearchByAllFilterTags',
            type: "Get",
            contentType: "application/json",
            dataType: "json",
            data: Main,
            success: function (results) {

            }
        })
    });

只要您没有在json数据中添加引号,您的数据就不会通过。

如果控制器上的模型匹配,这将起作用。

暂无
暂无

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

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