Binding en-GB dates in a HTTP GET

前端 未结 2 546
无人共我
无人共我 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!

提交回复
热议问题