asp.net-mvc-3 – 将值传递给控制器时,ASP.NET MVC datetime文化问题
|
我如何告诉我的控制器/模型解析datetime应该期望什么样的文化? 我正在使用一些this post来实现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>
}
我已经为此编辑了一个模板,来实现jquery datepicker: @model DateTime
@Html.TextBox("",Model.ToString("dd-MM-yyyy"),new { @class = "date" })
然后我创建这样的datepicker小部件. $(document).ready(function () {
$('.date').datepicker({ dateFormat: "dd-mm-yy" });
});
所有这一切都很好. 这里是问题开始的地方,这是我的控制器: [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.
}
这就是为什么我想以某种方式告诉我的控制器应该期望什么文化? public class MeterViewModel {
[Required]
public DateTime StartDate { get; set; }
[Required]
public DateTime EndDate { get; set; }
}
编辑:this link解释我的问题和一个很好的解决方案.感谢gdoron 解决方法您可以创建一个Binder扩展以处理文化格式的日期.这是我写的用于处理与十进制类型相同的问题的示例,希望你能得到这个想法 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中声明这个binder 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());
}
那么当模型绑定器必须做一些工作时,它会自动地知道该做什么. [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和Flash – 可以与.net进行快速通话
- asp.net – 如何强制实体框架插入标识列?
- asp.net – Request.Url.AbsoluteUri和重写的URL
- asp.net-mvc – 使用ASP.Net MVC中的模型绑定器更新父/子记
- asp.net – Microsoft WebMatrix和Visual Studio有什么区别
- asp.net-core – Visual Studio 2017 RC安装会中断Visual S
- asp.net-mvc – MVC ASP.NET或Razor
- ASP.Net自定义会话状态管理
- asp.net – 如何找到哪个控制器/操作发生错误?
- asp.net – 拥有专用应用程序池,将Web应用程序保留在一个默
