代码之家  ›  专栏  ›  技术社区  ›  Omu

来自GET请求的日期时间使用的格式与来自POST的格式不同

  •  1
  • Omu  · 技术社区  · 15 年前

    来自post的日期时间被正确绑定(根据我的计算机的格式)

    但是来自get的datetime值没有正确绑定,它使用了不同的格式

    my format is dd.MM.yyyy, in GET it uses MM.dd.yyyy instead
    
    I don't have this problem if I use the en-US format  (which is MM/dd/yyyy)
    

    有人知道怎么解决这个问题吗?

    这是MVC错误吗?(绑定get请求时不考虑区域性)

    1 回复  |  直到 15 年前
        1
  •  8
  •   Community Mohan Dere    8 年前

    不,好像不是虫子。您可以在此处获得更多详细信息: MVC DateTime binding with incorrect date format

    我一直在使用下面的ModelBinder来解决这个问题。

    public class CurrentCultureDateTimeBinder : IModelBinder
    {
        private const string PARSE_ERROR = "\"{0}\" is not a valid date";
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    
            if (valueProviderResult == null) return null;
    
            var date = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
    
            if (String.IsNullOrEmpty(date))
                return null;
    
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider.GetValue(bindingContext.ModelName));
    
            try
            {
                return DateTime.Parse(date);
            }
            catch (Exception)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format(PARSE_ERROR, bindingContext.ModelName));
                return null;
            }
        }
    }
    

    希望它有帮助。

    推荐文章