ASP.NET MVC的datetime文化传递的问题时,值回控制器 [英] ASP.NET MVC datetime culture issue when passing value back to controller
问题描述
我如何知道我的控制器/模型应该期待解析日期时间什么样的文化?
我使用了一些<一个href=\"http://blogs.msdn.com/b/stuartleeks/archive/2011/01/25/asp-net-mvc-3-integrating-with-the-jquery-ui-date-picker-and-adding-a-jquery-validate-date-range-validator.aspx\">this帖子落实jQuery的日期选择在我的MVC应用程序。
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" });
});
这一切工作正常。
All this works fine.
这里就是问题开始,这是我的控制器:
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; }
}
编辑:<一href=\"http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx\">this链接解释我的问题,也是一个很好的解决它以及。由于gdoron
this link explains my issue and a very good solution to it aswell. Thanks to gdoron
推荐答案
您可以创建一个活页夹的扩展来处理文化的日期格式。
You can create a Binder extension to handle the date in the culture format.
这是我写来处理与十进制类型相同的问题样本,希望得到您的想法
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());
}
然后当ModelBinder的已做了一些工作,它会自动知道该怎么做。
例如,这是包含类型小数的一些性质的模型的动作。我干脆什么也不做。
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的datetime文化传递的问题时,值回控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!