C# 派生属性上的自定义模型绑定不起作用
我有一个定制的ModelBinder(MVC3),它不会因为某种原因而被解雇。以下是相关代码: 查看C# 派生属性上的自定义模型绑定不起作用,c#,asp.net-mvc,asp.net-mvc-3,model-binding,C#,Asp.net Mvc,Asp.net Mvc 3,Model Binding,我有一个定制的ModelBinder(MVC3),它不会因为某种原因而被解雇。以下是相关代码: 查看 @model WebApp.Models.InfoModel @using Html.BeginForm() { @Html.EditorFor(m => m.Truck) } 编辑模板 @model WebApp.Models.TruckModel @Html.EditorFor(m => m.CabSize) ModelBinder public class Truc
@model WebApp.Models.InfoModel
@using Html.BeginForm()
{
@Html.EditorFor(m => m.Truck)
}
编辑模板
@model WebApp.Models.TruckModel
@Html.EditorFor(m => m.CabSize)
ModelBinder
public class TruckModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
throw new NotImplementedException();
}
}
public ActionResult Index(InfoModel model)
{
// model.Vehicle is *not* of type TruckModel!
}
Global.asax
protected void Application_Start()
{
...
ModelBinders.Binders.Add(typeof(TruckModel), new TruckModelBinder());
...
}
信息模型
public class InfoModel
{
public VehicleModel Vehicle { get; set; }
}
public class VehicleModel
{
public string Color { get; set; }
public int NumberOfWheels { get; set; }
}
public class TruckModel : VehicleModel
{
public int CabSize { get; set; }
}
车辆模型
public class InfoModel
{
public VehicleModel Vehicle { get; set; }
}
public class VehicleModel
{
public string Color { get; set; }
public int NumberOfWheels { get; set; }
}
public class TruckModel : VehicleModel
{
public int CabSize { get; set; }
}
卡车模型
public class InfoModel
{
public VehicleModel Vehicle { get; set; }
}
public class VehicleModel
{
public string Color { get; set; }
public int NumberOfWheels { get; set; }
}
public class TruckModel : VehicleModel
{
public int CabSize { get; set; }
}
控制器
public class TruckModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
throw new NotImplementedException();
}
}
public ActionResult Index(InfoModel model)
{
// model.Vehicle is *not* of type TruckModel!
}
为什么我的自定义ModelBinder没有启动?您必须将ModelBinder与基类相关联:
ModelBinders.Binders.Add(typeof(VehicleModel), new TruckModelBinder());
您的POST操作采用InfoModel参数,该参数本身具有VehicleModel类型的Vehicle属性。因此,MVC在绑定过程中不了解TruckModel
您可以查看一个实现多态模型绑定器的示例 完美,现在有意义了。谢谢你,达林,很快跟进。我尝试了这个,它在大多数情况下都有效,除了我的模型值都返回默认值/null。我将用我现在的代码更新OP中的代码。没关系,我将把它标记为答案,因为它解决了我最初的自定义ModelBinder未正确绑定的问题。我正在回滚我的编辑,并将在此新问题上创建一个新问题。再次感谢。。