将值传递回控制器时,ASP.NET MVC日期时间文化问题

Jim*_*lff 18 validation data-annotations jquery-ui-datepicker asp.net-mvc-3

我怎样才能告诉我的控制器/模型解析日期时应该具备哪种文化?

我正在使用这篇文章的一些内容将jquery datepicker实现到我的mvc应用程序中.

当我提交日期时,它"在翻译中丢失"我没有使用美国格式的日期,所以当它被发送到我的控制器时它只是变为空.

我有一个用户选择日期的表单:

@using (Html.BeginForm("List", "Meter", FormMethod.Get))
{
    @Html.LabelFor(m => m.StartDate, "From:")
    <div>@Html.EditorFor(m => m.StartDate)</div>

    @Html.LabelFor(m => m.EndDate, "To:")
    <div>@Html.EditorFor(m => m.EndDate)</div>
}
Run Code Online (Sandbox Code Playgroud)

我为此创建了一个编辑模板,以实现jquery datepicker:

@model DateTime
@Html.TextBox("", Model.ToString("dd-MM-yyyy"), new { @class = "date" }) 
Run Code Online (Sandbox Code Playgroud)

然后我创建像这样的datepicker小部件.

$(document).ready(function () {
    $('.date').datepicker({ dateFormat: "dd-mm-yy" });
});
Run Code Online (Sandbox Code Playgroud)

这一切都很好.

这是问题的起点,这是我的控制器:

[HttpGet]
public ActionResult List(DateTime? startDate = null, DateTime? endDate = null)
{
    //This is where startDate and endDate becomes null if the dates dont have the expected formatting.
}
Run Code Online (Sandbox Code Playgroud)

这就是为什么我想以某种方式告诉我的控制器应该期待什么样的文化?我的模特错了吗?我可以以某种方式告诉它使用哪种文化,比如数据注释属性?

public class MeterViewModel {
    [Required]
    public DateTime StartDate { get; set; }
    [Required]
    public DateTime EndDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

编辑:这个链接解释了我的问题,也是一个非常好的解决方案.感谢gdoron

gdo*_*ica 21

您可以使用IModelBinder更改默认模型绑定器以使用用户区域性

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

           return date;    
       }
   }
Run Code Online (Sandbox Code Playgroud)

而在Global.Asax写道:

ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());
ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeBinder());
Run Code Online (Sandbox Code Playgroud)

这个出色的博客上阅读更多信息,该博客描述了Mvc框架团队为所有用户实施默认文化的原因.

  • +1非常好的博客文章完全解释我的问题. (3认同)

Iri*_*dio 12

您可以创建一个Binder扩展来处理文化格式的日期.

这是我用Decimal类型处理同样问题的一个例子,希望你能得到这个想法

 public class DecimalModelBinder : IModelBinder
 {
   public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
   {
     ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
     ModelState modelState = new ModelState { Value = valueResult };
     object actualValue = null;
     try
     {
       actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
     }
     catch (FormatException e)
     {
       modelState.Errors.Add(e);
     }

     bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
     return actualValue;
  }
}
Run Code Online (Sandbox Code Playgroud)

更新

要使用它,只需在Global.asax中声明绑定器就像这样

protected void Application_Start()
{
  AreaRegistration.RegisterAllAreas();
  RegisterGlobalFilters(GlobalFilters.Filters);
  RegisterRoutes(RouteTable.Routes);

  //HERE you tell the framework how to handle decimal values
  ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());

  DependencyResolver.SetResolver(new ETAutofacDependencyResolver());
}
Run Code Online (Sandbox Code Playgroud)

然后,当模型绑定器必须做一些工作时,它将自动知道该做什么.例如,这是一个包含一些decimal类型属性的模型的动作.我什么都不做

[HttpPost]
public ActionResult Edit(int id, MyViewModel viewModel)
{
  if (ModelState.IsValid)
  {
    try
    {
      var model = new MyDomainModelEntity();
      model.DecimalValue = viewModel.DecimalValue;
      repository.Save(model);
      return RedirectToAction("Index");
    }
    catch (RulesException ex)
    {
      ex.CopyTo(ModelState);
    }
    catch
    {
      ModelState.AddModelError("", "My generic error message");
    }
  }
  return View(model);
}
Run Code Online (Sandbox Code Playgroud)


Rob*_*ent 10

出现此问题的原因是您在表单上使用GET方法.MVC中的QueryString Value Provider始终使用Invariant/US日期格式.请参阅:MVC DateTime绑定的日期格式不正确

有三种解决方案:

  1. 将您的方法更改为POST.
  2. 正如其他人所说,在提交之前将日期格式更改为ISO 8601"yyyy-mm-dd".
  3. 使用自定义绑定程序始终将查询字符串日期视为GB.如果这样做,您必须确保所有日期都采用该格式:

    public class UKDateTimeModelBinder : IModelBinder
    {
    private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
    /// <summary>
    /// Fixes date parsing issue when using GET method. Modified from the answer given here:
    /// https://stackoverflow.com/questions/528545/mvc-datetime-binding-with-incorrect-date-format
    /// </summary>
    /// <param name="controllerContext">The controller context.</param>
    /// <param name="bindingContext">The binding context.</param>
    /// <returns>
    /// The converted bound value or null if the raw value is null or empty or cannot be parsed.
    /// </returns>
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var vpr = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    
        if (vpr == null)
        {
            return null;
    
        }
    
        var date = vpr.AttemptedValue;
    
        if (String.IsNullOrEmpty(date))
        {
            return null;
        }
    
        logger.DebugFormat("Parsing bound date '{0}' as UK format.", date);
    
        // Set the ModelState to the first attempted value before we have converted the date. This is to ensure that the ModelState has
        // a value. When we have converted it, we will override it with a full universal date.
        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider.GetValue(bindingContext.ModelName));
    
        try
        {
            var realDate = DateTime.Parse(date, System.Globalization.CultureInfo.GetCultureInfoByIetfLanguageTag("en-GB"));
    
            // Now set the ModelState value to a full value so that it can always be parsed using InvarianCulture, which is the
            // default for QueryStringValueProvider.
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, new ValueProviderResult(date, realDate.ToString("yyyy-MM-dd hh:mm:ss"), System.Globalization.CultureInfo.GetCultureInfoByIetfLanguageTag("en-GB")));
    
            return realDate;
        }
        catch (Exception)
        {
            logger.ErrorFormat("Error parsing bound date '{0}' as UK format.", date);
    
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("\"{0}\" is invalid.", bindingContext.ModelName));
            return null;
        }
    }
    }
    
    Run Code Online (Sandbox Code Playgroud)