How do I get a view to put a date-formatted string into a route and pass it to a controller method parameter of type DateTime in some way? That is string→datetime. The MVC default Modelbinder does not provide such a mechanism, so we want to customize a modelbinder.
First, in the foreground view, assign a date-formatted string to the date variable in the route:
@Html. ActionLink ("Incoming date format is 2014-06-19","date",new"2014-06-19"})
In the Controller method, you want to receive the date variable as follows:
Public ActionResult Date (DateTime date) { viewdata["date"] = date; return View (); }
The custom Modelbinder implements the Imodelbinder interface:
usingSystem;usingSYSTEM.WEB.MVC;namespacemvcapplication1.extension{ Public classDatetimemodelbinder:imodelbinder { Public stringFormat {Get;Private Set; } PublicDatetimemodelbinder (stringformat) { This. Format =format; } Public ObjectBindmodel (ControllerContext controllercontext, Modelbindingcontext bindingcontext) {//from Valueprovider, the model name is key, which gets the value of the model varValue =BindingContext.ValueProvider.GetValue (bindingcontext.modelname); returnDateTime.ParseExact ((string) value. Attemptedvalue, This. Format,NULL); } }}
Above, through the constructor injection format, through the use of the property format, in the Bindmodel () method to remove the value in the Valueprovider, and then converted to a datetime type.
The next question is: How can DateTime date be used to customize the Modelbinder? To do this, we need a class derived from Custommodelbinderattribute, overriding the Getbinder () method of Custommodelbinderattribute.
usingSYSTEM.WEB.MVC;namespacemvcapplication1.extension{ Public classDatetimeattribute:custommodelbinderattribute { Public stringFormat {Get;Private Set; } PublicDatetimeattribute (stringformat) { This. Format =format; } Public OverrideImodelbinder Getbinder () {return NewDatetimemodelbinder ( This. Format); } }}
Then hit the datetimeattribute on the controller method parameter:
Public ActionResult Date ([DateTime ("yyyy-mm-dd")]datetime date) { viewdata[ " Date "] = date; return View (); }
As a result, you can eventually use the datetime type from the Controller method in the ViewData in the view:
@{ var date = (DateTime) viewdata["date";} <span> the Date Received is:</span><span> @date. ToShortDateString () </span>