我有一个简单的模式,使用select2从服务器获取产品列表.用户可以多次选择产品,然后点击“确定”以优化搜索.
我的以下设置从模态中获取数据,并使用强类型视图模型对Controller操作执行ajax调用,该模型与JS尝试通过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(这实际上使日期不再绑定)
我究竟做错了什么?
解决方法:
尝试在Ajax请求中添加contentType:“application / json”
$.ajax({
...
contentType: "application/json",
...
});