In some ways, how can a view put a string in the date format into a route and pass it to the DateTime-Type Controller method parameter? That is, string → DateTime. The default ModelBinder of MVC does not provide such a mechanism, so we need to customize a ModelBinder.
First, in the foreground view, assign a string that complies with the date format to the date variable in the route:
@ Html. ActionLink ("input Date format: 2014-06-19", "date", new {Date = "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:
Using System; using System. web. mvc; namespace MvcApplication1.Extension {public class DateTimeModelBinder: IModelBinder {public string Format {get; private set;} public DateTimeModelBinder (string format) {this. format = format;} public object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) {// from ValueProvider, the model name is key and the model value var value = bindingContext is obtained. valueProvider. getValue (bindingContext. modelName); return DateTime. parseExact (string) value. attemptedValue, this. format, null );}}}
The preceding section uses the constructor injection format and the attribute format to retrieve the value of ValueProvider in the BindModel () method and convert it to the DateTime type.
The following question is: How can I use the custom ModelBinder for DateTime date? Therefore, we need a class derived from CustomModelBinderAttribute to override the GetBinder () method of CustomModelBinderAttribute.
using System.Web.Mvc;namespace MvcApplication1.Extension{ public class DateTimeAttribute : CustomModelBinderAttribute { public string Format { get; private set; } public DateTimeAttribute(string format) { this.Format = format; } public override IModelBinder GetBinder() { return new DateTimeModelBinder(this.Format); } }}
Call DateTimeAttribute to the Controller method parameters:
public ActionResult Date([DateTime("yyyy-MM-dd")]DateTime date) { ViewData["Date"] = date; return View(); }
As a result, the DateTime type transmitted from the Controller method can be used in the view as follows in ViewData:
@ {Var date = (DateTime) ViewData ["Date"] ;}< span> the date received is: </span> <span> @ date. tow.datestring () </span>