I have URL:
http://localhost/Page?id=&created_date=27-09-2017
Date format for created_date
above is "dd-MM-yyyy".
Meanwhile, my controller:
public ActionResult Page(string id = null, DateTime? created_date = null)
{
...
}
Well, because the URL date format is "dd-MM-yyyy", I cannot retrieve value of created_date
(still null) in my controller. But if I change the URL date format into "MM-dd-yyyy", created_date
successfully filled (27 Sept 2017). For example:
http://localhost/Page?id=&created_date=09-27-2017
How do I change globally this mechanism to "dd-MM-yyyy"? Because there are so many URL patterns like this. I don't want to change the URL date format manually.
--- Update (add custom model binder) ---
Here my Global.asax.cs
:
protected void Application_Start()
{
var binder = new DateTimeModelBinder("dd-MM-yyyy");
ModelBinders.Binders.Add(typeof(DateTime), binder);
ModelBinders.Binders.Add(typeof(DateTime?), binder);
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
And DateTimeModelBinder
class:
public class DateTimeModelBinder : DefaultModelBinder
{
private string _customFormat;
public DateTimeModelBinder(string customFormat)
{
_customFormat = customFormat;
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
return DateTime.ParseExact(value.AttemptedValue, _customFormat, CultureInfo.InvariantCulture);
}
}
Thanks in advance