asp.net mvc:默认模型绑定器问题
我有一个 MVC 3 视图,它显示可以按日期过滤的项目列表。
该过滤器是一个文本框,已通过 jQueryUI 转换为日期选择器。
视图:
<%= Html.TextBoxFor(model => model.ReportedDate, new { @class = "datepicker" })%>
脚本:
$(".datepicker").datepicker({
dateFormat: 'dd/mm/yy',
changeYear: true,
changeMonth: true
});
单击按钮后,我抓取文本框的值并将其作为 GET 请求的查询字符串参数发送到我的控制器操作:
MyController/Search?reportedDate=30/05/2011
控制器操作:
public ActionResult Search(DateTime? reportedDate)
由此我期望默认模型绑定器转换 reportedDate
查询参数为可为 null 的 DateTime(在此上下文中 null 表示所有日期或无过滤器)。
然而事实并非如此。 reportedDate
始终为空。我可以深入研究 Request.QueryString
并使用 DateTime.TryParse
手动进行转换,这是我当前的解决方法,但我不明白为什么它在第一个中失败地方。
客户端和服务器之间的日期格式没有区别,并且还有其他数据类型(字符串和整数)的其他(此处省略但在实际代码中存在)过滤器参数,并且它们的处理没有问题。
为什么 DateTime 很麻烦有什么建议吗?
I've got a MVC 3 view which displays a list of items that can be filtered by date.
The filter is a textbox which has been jQueryUI-fied into a date picker.
View:
<%= Html.TextBoxFor(model => model.ReportedDate, new { @class = "datepicker" })%>
Script:
$(".datepicker").datepicker({
dateFormat: 'dd/mm/yy',
changeYear: true,
changeMonth: true
});
Upon a button click, I grab the value of the text box and send it to my controller action as a query string parameter of a GET request:
MyController/Search?reportedDate=30/05/2011
Controller Action:
public ActionResult Search(DateTime? reportedDate)
From this I expect the default model binder to convert the reportedDate
query parameter to a nullable DateTime (null in this context representing all dates or no filter).
However this is not the case. reportedDate
is always null. I can drill into Request.QueryString
and do the conversion manually using DateTime.TryParse
, which is my current work around, but I don't understand why it's failing in the first place.
There's no difference in the date format between the client and server and there are other (omitted here but present in the actual code) filter parameters of other data types (string and int) and they get processed without a problem.
Any suggestions why DateTime is troublesome?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
维利是对的。如果您想使用该日期格式,您将需要一个适用于您的日期时间的自定义模型绑定器。看一下这里:
如何指定模型绑定的日期格式?
Veli is right. If you want to use that Date format, you'll need a custom model binder for your DateTime. Take a look here:
How to specify date format for model binding?
您可以使用以下方式向路由表添加新路由
,然后您的 url 将变为
,这将使您的控制器操作捕获 reportingDate 的值
,但您必须更改您在日期选择器中使用的日期格式
you can add a new route to routing table using
then the your url will become
that will make your controller action catch the value of reportedDate
but you have to chaneg the date format you used in your date picker
是的,问题毕竟是日期格式,看起来预期的日期格式字符串是
mm/dd/yyyy
并且日期输入为日/月/年
Right, well the problem is the date format after all, it looks like the expected date format string is
mm/dd/yyyy
and the date is coming in asdd/mm/yyyy