派生属性上的自定义模型绑定不起作用
我有一个自定义的ModelBinder(MVC3),由于某种原因没有被解雇。 以下是相关的代码:
视图
@model WebApp.Models.InfoModel @using Html.BeginForm() { @Html.EditorFor(m => m.Truck) }
EditorTemplate
@model WebApp.Models.TruckModel @Html.EditorFor(m => m.CabSize)
ModelBinder的
public class TruckModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { throw new NotImplementedException(); } }
Global.asax中
protected void Application_Start() { ... ModelBinders.Binders.Add(typeof(TruckModel), new TruckModelBinder()); ... }
InfoModel
public class InfoModel { public VehicleModel Vehicle { get; set; } }
VehicleModel
public class VehicleModel { public string Color { get; set; } public int NumberOfWheels { get; set; } }
TruckModel
public class TruckModel : VehicleModel { public int CabSize { get; set; } }
调节器
public ActionResult Index(InfoModel model) { // model.Vehicle is *not* of type TruckModel! }
为什么我的自定义ModelBinder不能解雇?
您必须将模型绑定器与基类关联:
ModelBinders.Binders.Add(typeof(VehicleModel), new TruckModelBinder());
您的POST操作采用InfoModel参数,该参数本身具有VehicleModel类型的Vehicle属性。 因此,MVC在绑定过程中不了解TruckModel。
您可以看一下实现多态模型绑定器的示例的以下post 。
- 如何对ASP.NET Core控制器或模型对象进行unit testing?
- 在OwinStartup之后为新租户添加Owin管道中间件
- JsonConvert.DeserializeObject特殊字符未终止字符串。 预期分隔符:
- Moq模拟和跟踪会话值
- 如何使用带复选框和下拉菜单的自动回发function?
- WebApi,Autofac,System.Web.Http.Filters.ActionFilterAttribute每个请求的实例
- 在ASP.Net Identity 2.0上包含属性UserManager.Users.ToListAsync和UserManager.FindByIdAsync
- 从adlds实例validationasp.net mvc 5应用程序
- IEnumerable VS IList VS IQueryable