为了使对象被默认模型绑定器正确绑定,它必须具有默认的无参数构造函数:
public class EMailAddress
{
public string Address { get; set; }
}
如果您想使用模型作为您展示的模型,您需要编写一个自定义模型绑定器来处理转换:
public class EmailModelBinder : DefaultModelBinder
{
public override object BindModel(
ControllerContext controllerContext,
ModelBindingContext bindingContext
)
{
var email = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (email != null)
{
return new EMailAddress(email.AttemptedValue);
}
return new EMailAddress(string.Empty);
}
}
将在以下位置注册Application_Start
:
ModelBinders.Binders.Add(typeof(EMailAddress), new EmailModelBinder());
并像这样使用:
public class HomeController : Controller
{
public ActionResult Index(EMailAddress email)
{
return View();
}
}
现在,当您查询/Home/Index?email=foo@bar.baz
操作参数时,应该正确绑定。
现在的问题是:当您可以拥有我最初展示的视图模型时,您真的想编写所有这些代码吗?