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

前端 未结 7 1320
既然无缘
既然无缘 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:32

    Why not simply inspect the culture of the data and convert it as such? This simple approach allowed me to use strongly typed dates in models, show action links and edit fields in the desired locale and not have to fuss at all binding it back into a strongly typed DateTime:

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

提交回复
热议问题