自定义模型绑定派生属性不工作 [英] Custom model binding on derived property not working

查看:111
本文介绍了自定义模型绑定派生属性不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的模型绑定器(MVC3)没有被解雇的某些原因。以下是code的相关部分:

I have a custom ModelBinder (MVC3) that isn't getting fired for some reason. Here are the relevant pieces of code:

查看

@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的射击?

Why isn't my custom ModelBinder firing?

推荐答案

您必须将模型绑定与基类关联:

You will have to associate the model binder with the base class:

ModelBinders.Binders.Add(typeof(VehicleModel), new TruckModelBinder());

您POST操作采用其本身具有的类型VehicleModel的车辆属性的InfoModel参数。因此MVC有结合过程中没有TruckModel的知识。

Your POST action takes an InfoModel parameter which itself has a Vehicle property of type VehicleModel. So MVC has no knowledge of TruckModel during the binding process.

您可以看一看的<一个href=\"http://stackoverflow.com/questions/6484972/viewmodel-with-listbaseclass-and-editor-templates/6485552#6485552\">following发布implemeting多态模型绑定的例子。

这篇关于自定义模型绑定派生属性不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆