[英]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.