ASP.NET MVC datetime culture issue when passing value back to controller

前端 未结 7 1058
既然无缘
既然无缘 2020-12-05 18:32

How can i tell my controller/model what kind of culture it should expect for parsing a datetime?

I was using some of this post to implement jquery d

相关标签:
7条回答
  • 2020-12-05 19:36

    you can change the default model binder to use the user culture using IModelBinder

       public class DateTimeBinder : IModelBinder
       {
           public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
           {
               var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
               var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
    
               return date;    
           }
       }
    

    And in the Global.Asax write:

    ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());
    ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeBinder());
    

    Read more at this excellent blog that describe why Mvc framework team implemented a default Culture to all users.

    0 讨论(0)
提交回复
热议问题