我有兩個視圖創建&編輯。 兩者都有一個叫做ModelType
的隱藏字段,可以在我的模型聯編程序中使用它來綁定所有的子類。在MVC4中使用@Html.Hidden的空引用剃鬚刀
此隱藏字段在編輯視圖中正常工作,但在創建視圖中無法正常工作。 我得到一個null reference exception
在行:
@Html.Hidden("ModelType" , Model.GetType().AssemblyQualifiedName)
在創建視圖。
請幫助這裏出了什麼問題。
Edit.cshtml
@using PartyBiz.Models.Objects
@model Organization
@using (Html.BeginForm("Edit", "Organization", FormMethod.Post))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Edit Organization</legend>
<div class="editor-label">
@Html.LabelFor(model => model.C)
@Html.TextBoxFor(model => model.C, new { @class = "txt"})
@Html.ValidationMessageFor(model => model.C)
</div> <br />
<div class="editor-label">
@Html.LabelFor(model => model.N)
@Html.TextBoxFor(model => model.N, new { @class = "txt"})
@Html.ValidationMessageFor(model => model.N)
</div> <br />
<div class="editor-label">
@Html.LabelFor(model => model.D)
@Html.TextBoxFor(model => model.D, new { @class = "txt"})
@Html.ValidationMessageFor(model => model.D)
</div>
<br />
@Html.HiddenFor(model=> model.PID)
@Html.Hidden("ModelType" , Model.GetType().AssemblyQualifiedName)
<input type="submit" value="Edit" />
</fieldset>
}
Create.cshtml
@using PartyBiz.Models.Objects
@model Organization
@using (Html.BeginForm("Create", "Organization", FormMethod.Post))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Create a New Organization</legend>
<div class="editor-label">
@Html.LabelFor(model => model.C)
@Html.TextBoxFor(model => model.C, new { @class = "txt"})
@Html.ValidationMessageFor(model => model.C)
</div> <br />
<div class="editor-label">
@Html.LabelFor(model => model.N)
@Html.TextBoxFor(model => model.N, new { @class = "txt"})
@Html.ValidationMessageFor(model => model.N)
</div> <br />
<div class="editor-label">
@Html.LabelFor(model => model.D)
@Html.TextBoxFor(model => model.D, new { @class = "txt"})
@Html.ValidationMessageFor(model => model.D)
</div>
<br />
<input type="submit" value="Create" />
@Html.Hidden("ModelType" , Model.GetType().AssemblyQualifiedName)
</fieldset>
}
模型綁定
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.ValueProvider.ContainsPrefix("ModelType"))
{
//get the model type
var typeName = (string)bindingContext
.ValueProvider
.GetValue("ModelType")
.ConvertTo(typeof(string));
var modelType = Type.GetType(typeName);
//tell the binder to use it
bindingContext.ModelMetadata =
ModelMetadataProviders
.Current
.GetMetadataForType(null, modelType);
}
return base.BindModel(controllerContext, bindingContext);
}
請將您的控制器操作顯示爲創建視圖! – nemesv