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?
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:
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 as dd/mm/yyyy
you can add a new route to routing table using
routes.MapRoute(
"SearchRoute",
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", reportedDate = UrlParameter.Optional}
);
then the your url will become
MyController/Search/30-05-2011
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.