我有两个视图,创建和编辑。两者都有一个隐藏字段ModelType
,用于在我的模型绑定器中使用它来绑定所有子类。
此隐藏字段在编辑视图中工作正常,但在创建视图中不工作。我正在null reference exception
排队:
@Html.Hidden("ModelType" , Model.GetType().AssemblyQualifiedName)
在创建视图中。
这里有什么问题?
编辑.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>
}
创建.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);
}