【发布时间】:2011-08-30 00:51:42
【问题描述】:
我有一个非常简单的 DefaultModelBinder 实现,我需要它来触发一些自定义验证。
public class MyViewModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ModelStateDictionary modelState = bindingContext.ModelState;
var model = (MyViewModel)base.BindModel(controllerContext, bindingContext);
var result = ValidationFactory.ForObject<MyViewModel>().Validate(model);
CustomValidation(result, modelState);
return model;
}
}
MyViewModel 是一个公开的密封类。 模型绑定器以这种方式在 Global.asax 中注册:
ModelBinders.Binders.Add(typeof(MyViewModel), new MyViewModelBinder());
问题是模型永远不会被填充!但是 MVC 默认模型绑定器(我删除了 global.asax 中的注册)工作正常。
这是视图 HTML:
<table>
<tr>
<td><label for="Name">Name</label></td>
<td><input id="Name" name="Name" type="text" value="" /></td>
</tr>
<tr>
<td><label for="Code">Code</label></td>
<td><input id="Code" name="Code" type="text" value="" /></td>
</tr>
</table> </div>
每个字段都匹配模型的一个属性。
【问题讨论】:
标签: asp.net-mvc-2 defaultmodelbinder