У меня есть два вида Создать & Редактировать. Оба имеют скрытое поле под названием ModelType
, чтобы использовать его в моем связующем устройстве для связывания всех подклассов.Нулевая ссылка с @ Html.Hidden в MVC4 Razor
Это скрытое поле отлично работает в режиме редактирования, но не в режиме создания. Я получаю 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