Binding en-GB dates in a HTTP GET

前端 未结 2 532
无人共我
无人共我 2020-12-09 21:30

I\'m having a nightmare of a time with Dates. Were based in the UK, so our date format is dd/MM/yyyy. This is what users will type into the form when they want a certain dat

相关标签:
2条回答
  • 2020-12-09 21:49

    Got a solution, thanks to @Jon for the pointers:

    public class GBDateModelBinder : IModelBinder
    {
    
        #region IModelBinder Members
    
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string dateString = controllerContext.HttpContext.Request.QueryString[bindingContext.ModelName];
            if (string.IsNullOrEmpty(dateString))
                     dateString = controllerContext.HttpContext.Request.Form[bindingContext.ModelName];
            DateTime dt = new DateTime();
            bool success = DateTime.TryParse(dateString, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out dt);
            if (success)
            {
                return dt;
            }
            else
                {
                return null;
            }
        }
    
        #endregion
    }
    

    then register in global.asax:

    ModelBinders.Binders.Add(typeof(DateTime), new GBDateModelBinder());
    

    UPDATE

    altered this to allow for the same issue when POSTing!

    0 讨论(0)
  • 2020-12-09 21:57

    In addition to Liam's answer:

    For those who are still having this issue (!) and are trying to bind to a Nullable DateTime, make sure you register the correct type in global.asax:

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

    Had me stumped for 15 minutes!

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