2011-11-10 65 views
1

我有一個自定義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! 
} 

爲什麼不是我的自定義模型綁定器發射?

回答

6

你必須與基類模型綁定關聯:

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

你的POST操作採用其本身具有類型VehicleModel的車輛財產InfoModel參數。因此,MVC在綁定過程中不瞭解TruckModel。

您可以看看following post實現多態模型聯編程序的示例。

+0

完美,現在有道理。謝謝Darin。 –

+0

快速跟進。我嘗試了這一點,它的作用大部分,除了我的模型值都返回default/null。我將用我現在擁有的更新OP中的代碼。 –

+0

沒關係,我打算將其標記爲答案,因爲它解決了我自定義ModelBinder的原始問題未被正確綁定的問題。我回滾我的編輯,並將在這個新問題上創建一個新問題。再次感謝。 –