从URL参数ASP.NET更改默认的DateTime格式检索

时间:2017-09-14 09:43:52

标签: c# asp.net .net

我有网址:

http://localhost/Page?id=&created_date=27-09-2017

上面created_date的日期格式为“dd-MM-yyyy”。

同时,我的控制器:

public ActionResult Page(string id = null, DateTime? created_date = null)
{
...
}

好吧,因为URL日期格式是“dd-MM-yyyy”,我无法在我的控制器中检索created_date(仍然为空)的值。但是,如果我将URL日期格式更改为“MM-dd-yyyy”,created_date已成功填写(2017年9月27日)。例如:

http://localhost/Page?id=&created_date=09-27-2017

如何将此机制全局更改为“dd-MM-yyyy”?因为有这么多的URL模式。我不想手动更改URL日期格式。

---更新(添加自定义模型活页夹)---

这是我的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);
}

DateTimeModelBinder课程:

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);
     }
}

提前致谢

0 个答案:

没有答案
相关问题