MVC的UpdateModel当名称不匹配 [英] MVC UpdateModel when the names don't match up
问题描述
让我们说你有一个模型,看起来有点像这样的:
Let's say that you have a Model that looks kind of like this:
public class MyClass {
public string Name { get; set; }
public DateTime MyDate { get; set; }
}
这是Visual Studio中为您提供了默认的编辑模板是数值指明MyDate
属性的纯文本框。这是一切优秀和良好的,但让我们说,你需要拆分成它的月/日/年的组件,并且您的形式如下:
The default edit template that Visual Studio gives you is a plain textbox for the MyDate
property. This is all fine and good, but let's say that you need to split that up into it's Month/Day/Year components, and your form looks like:
<label for="MyDate">Date:</label>
<%= Html.TextBox("MyDate-Month", Model.MyDate.Month) %>
<%= Html.TextBox("MyDate-Day", Model.MyDate.Day) %>
<%= Html.TextBox("MyDate-Year", Model.MyDate.Year) %>
在此被提交,到的UpdateModel
通话将无法工作,因为没有为数值指明MyDate个月的定义
。有没有办法将自定义粘结剂添加到项目中来处理这种情况,或者如果HTML输入名称不同(无论何种原因)?
When this is submitted, a call to UpdateModel
won't work, since there isn't a definition for MyDate-Month
. Is there a way to add a custom binder to the project to handle situations like this, or if the HTML inputs are named differently (for whatever reasons)?
一个解决办法,我发现是使用JavaScript注入一个隐藏的输入到该地连接了场,并正确命名之前提交的形式,但感觉错了。
One workaround I've found is to use JavaScript to inject a hidden input into the form before submission that concatenates the fields and is named properly, but that feels wrong.
推荐答案
我会建议你自定义的模型绑定:
I would suggest you a custom model binder:
using System;
using System.Globalization;
using System.Web.Mvc;
public class MyClassBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var model = (MyClass)base.CreateModel(controllerContext, bindingContext, modelType);
var day = bindingContext.ValueProvider["MyDate-Day"];
var month = bindingContext.ValueProvider["MyDate-Month"];
var year = bindingContext.ValueProvider["MyDate-Year"];
var dateStr = string.Format("{0}/{1}/{2}", month.AttemptedValue, day.AttemptedValue, year.AttemptedValue);
DateTime date;
if (DateTime.TryParseExact(dateStr, "MM/dd/yyyy", null, DateTimeStyles.None, out date))
{
model.MyDate = date;
}
else
{
bindingContext.ModelState.AddModelError("MyDate", "MyDate has invalid format");
}
bindingContext.ModelState.SetModelValue("MyDate-Day", day);
bindingContext.ModelState.SetModelValue("MyDate-Month", month);
bindingContext.ModelState.SetModelValue("MyDate-Year", year);
return model;
}
}
这简化了您的控制器动作:
This simplifies your controller action to:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyAction(MyClass myClass)
{
if (!ModelState.IsValid)
{
return View(myClass);
}
// Do something with myClass
return RedirectToAction("success");
}
和在Global.asax中注册粘结剂:
And register the binder in Global.asax:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ModelBinders.Binders.Add(typeof(MyClass), new MyClassBinder());
}
这篇关于MVC的UpdateModel当名称不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!