繁体   English   中英

asp.net mvc: 默认model binder问题

[英]asp.net mvc: default model binder problem

我有一个 MVC 3 视图,它显示可以按日期过滤的项目列表。

过滤器是一个文本框,它已经被 jQueryUI 填充到日期选择器中。

看法:

<%= Html.TextBoxFor(model => model.ReportedDate, new { @class = "datepicker" })%>

脚本:

$(".datepicker").datepicker({
        dateFormat: 'dd/mm/yy',
        changeYear: true,
        changeMonth: true
});

单击按钮后,我获取文本框的值并将其作为 GET 请求的查询字符串参数发送到我的 controller 操作:

MyController/Search?reportedDate=30/05/2011

Controller 动作:

public ActionResult Search(DateTime? reportedDate)

由此,我期望默认的 model 绑定器将reportedDate日期查询参数转换为可为空的日期时间(在此上下文中为空,表示所有日期或无过滤器)。

然而,这种情况并非如此。 reportedDate日期始终为 null。 我可以深入Request.QueryString并使用DateTime.TryParse手动进行转换,这是我目前的工作,但我不明白为什么它首先会失败。

客户端和服务器之间的日期格式没有区别,并且还有其他数据类型(字符串和 int)的其他过滤参数(此处省略,但在实际代码中存在),它们可以毫无问题地处理。

有什么建议为什么 DateTime 很麻烦?

维利是对的。 如果您想使用该日期格式,您需要为您的日期时间定制 model 活页夹。 看看这里:

如何为 model 绑定指定日期格式?

对,问题毕竟日期格式,看起来预期的日期格式字符串是mm/dd/yyyy ,而日期是dd/mm/yyyy

您可以使用向路由表添加新路由

routes.MapRoute(
"SearchRoute", 
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", reportedDate = UrlParameter.Optional} 
);

那么您的 url 将变为

MyController/Search/30-05-2011

这将使您的 controller 操作捕获报告日期的值

但您必须更改您在日期选择器中使用的日期格式

暂无
暂无

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

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