在我的ASP.Net MVC3項目中,我創建了一個綁定基本模型的ModelBinder。在我的視圖中,我從模型中創建一個對象,從我的基本模型繼承。現在我不想知道哪個模型是通過我的ModelBinder中的反射創建的,當我按下提交按鈕時,但是如何?如何將http請求轉換爲正確的對象?
ModelBinder的:
public class MBTestBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
//need to know which Model was created -> convert into the right object
//reflection?
}
}
型號:
[ModelBinder(typeof(MBTestBinder))]
public class MBTest
{
public string Name { get; set; }
public MBTest() {}
}
public class MBAbl : MBTest
{
public MBAbl() {}
public string House { get; set; }
}
查看:
@model ModelBinderProject.Models.MBTest
@using (Html.BeginForm("Index", "Home")) {
<fieldset>
<div class="editor-field">
@Html.EditorForModel(Model)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
控制器:
public ActionResult Create(MBTest testItem)
{
//on init get a view from a class that hast inherit the class MBTest
if (testItem.Name == null) testItem = new MBAbl();
return View(testItem);
}
編輯:
與bindingContext.ValueProvider.GetValue("House")
我可以得到表的價值,但bindingContext.ModelType
認爲我的模型是MBTest
'''''bindingContext.ModelType'只返回基類 - 沒有工作:-( – jwillmer 2011-06-14 10:40:10
@myName更新回答 – Eranga 2011-06-14 14:46:47
@Eranga'UpdateModel(..)'再次調用ModelBinder,所以ModelBinder獲取'bindingContext.Model' 。但是,這意味着這種觀點。 第一次查看有兩種形式(House&Name)。當我按提交時,模型綁定器不檢測繼承類,只有基礎模型。 – jwillmer 2011-06-14 15:00:37