将值传递回控制器时的 ASP.NET MVC 日期时间文化问题 [英] ASP.NET MVC datetime culture issue when passing value back to controller

查看:20
本文介绍了将值传递回控制器时的 ASP.NET MVC 日期时间文化问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何告诉我的控制器/模型解析日期时间应该期望什么样的文化?

我使用了一些 这篇文章 在我的 mvc 应用程序中实现 jquery datepicker.

I was using some of this post to implement jquery datepicker into my mvc application.

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

When i submit the date it gets "lost in translation" i'm not using the US formatting for the date, so when it gets sent to my controller it simply becomes null.

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

I have a form where the user chooses a date:

@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>
}

我为此制作了一个编辑模板,以实现 jquery 日期选择器:

I've made an edit template for this, to implement the jquery datepicker:

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

然后我像这样创建日期选择器小部件.

I then create the datepicker widgets like this.

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

一切正常.

这里是问题开始的地方,这是我的控制器:

Here is where the problems start, this is my controller:

[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.
}

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

This is why i would like to somehow tell my controller what culture it should expect? Is my model wrong? can i somehow tell it which culture to use, like with the data annotation attributes?

public class MeterViewModel {
    [Required]
    public DateTime StartDate { get; set; }
    [Required]
    public DateTime EndDate { get; set; }
}

<小时>

此链接 解释了我的问题以及一个很好的解决方案.感谢 gdoron


this link explains my issue and a very good solution to it aswell. Thanks to gdoron

推荐答案

您可以创建一个 Binder 扩展来处理区域性格式的日期.

You can create a Binder extension to handle the date in the culture format.

这是我写的一个示例,用于处理 Decimal 类型的相同问题,希望您能理解

This is a sample I wrote to handle the same problem with Decimal type, hope you get the idea

 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;
  }
}

更新

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

To use it simply declare the binder in Global.asax like this

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());
}

然后当模型绑定器必须做一些工作时,它会自动知道要做什么.例如,这是一个操作,其模型包含一些十进制类型的属性.我只是什么都不做

Then when the modelbinder has to do some work, it will know automatically what to do. For example, this is an action with a model containing some properties of type decimal. I simply do nothing

[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);
}

这篇关于将值传递回控制器时的 ASP.NET MVC 日期时间文化问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆