我有一个简单的模式,它使用select2从服务器获取产品列表。用户可以多次选择产品,然后点击“确定”以优化搜索。
我的以下设置从模态中获取数据,并使用强类型视图模型对Controller操作执行ajax调用,该模型与JS尝试通过ajax调用发送的内容相匹配。
的Ajax:
var exploreFilters = {
"type" : exploreType,
"products" : $('#s2id_select2-products').select2('data'),
"locations" : $("#page-report__data").data("criteria__locations"),
"companies" : $("#page-report__data").data("criteria__companies"),
"usertypes" : $("#page-report__data").data("criteria__usertypes"),
"groupusers" : $("#page-report__data").data("criteria__groupusers"),
"datestart" : $("#page-report__data").data("criteria__datestart"),
"dateend" : $("#page-report__data").data("criteria__dateend")
};
$.ajax({
dataType: "html",
type: "POST",
url: "/Report/Group/FilteredView",
data: exploreFilters,
success: function(html) {
if($.trim(html) === "")
$targetSection.html('<div class="page-report__empty">No data found. Please adjust your search filters and try again.</div>');
else
$targetSection.html(html);
},
error: function(xhr, text, err) {
if(text === "timeout")
$targetSection.html('<div class="page-report__empty">The request timed out. Please try again.</div>');
else
$targetSection.html('<div class="page-report__empty">There has been an error.</div>');
}
});
在ajax调用进入控制器之前,我检查了exploreFilters的内容和结构:
以下是表单数据在POST请求中的显示方式:
另一方面,我得到了一个控制器,它采用类似于exploreFilters的结构的强类型参数:
public ActionResult FilteredView(ReportCriteriaViewModel criteria)
{
throw new NotImplementedException();
}
我的强类型视图模型:
public class ReportCriteriaViewModel
{
public ProductViewModel[] Products { get; set; }
public string[] Locations { get; set; }
public string[] Companies { get; set; }
public string UserTypes { get; set; }
public string GroupUsers { get; set; }
public string DateStart { get; set; }
public string DateEnd { get; set; }
}
public class ProductViewModel
{
public Guid Id { get; set; }
public string Text { get; set; }
}
一旦控制器动作被击中,我可以看到DateStart和DateEnd已成功绑定,但不是我的产品列表。
我无法更改json请求的数据类型,它必须是html,因为我的控制器操作将返回html。
我尝试更改Id和Text上的大小写,JSON.stringify(这实际上使日期不再绑定)
我做错了什么?
答案 0 :(得分:1)
尝试在Ajax请求中添加contentType:“application / json”
$.ajax({
...
contentType: "application/json",
...
});
答案 1 :(得分:0)
问题在于如何序列化列表:
products[0][id]
products[0][text]
您需要以这种格式发送您的列表:
products[0].id
products[0].text
id
和text
应为属性,不包含[]
,否则将其视为二维数组的索引。
答案 2 :(得分:0)
你应该试试
contentType: "application/json; charset=utf-8"
在$ .ajax调用的选项中
$.ajax({
dataType: "html",
type: "POST",
url: "/Report/Group/FilteredView",
data: exploreFilters,
contentType: "application/json; charset=utf-8" ....