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

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

    I have a updated solution for MVC5 based on the Post of @gdoron. I will share it in case anyone else is looking for this. The class inherits from DefaultModelBinder and has exception handling for invalid dates. It also can handle null values:

    public class DateTimeModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            object result = null;
    
            var modelName = bindingContext.ModelName;
            var attemptedValue = bindingContext.ValueProvider.GetValue(modelName)?.AttemptedValue;
    
            // in datetime? binding attemptedValue can be Null
            if (attemptedValue != null && !string.IsNullOrWhiteSpace(attemptedValue))
            {
                try
                {
                    var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                    result = DateTime.Parse(value.AttemptedValue, CultureInfo.CurrentCulture);
                }
                catch (FormatException e)
                {
                    bindingContext.ModelState.AddModelError(modelName, e);
                }
            }
    
            return result;
        }
    }
    

    And just like the mentioned sample in the Global.Asax write

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

提交回复
热议问题