如果VS为[HttpGet] Create
创建强类型视图,我会按如下方式获取模型的标记。
请注意,为简洁起见,代码已经过简化。重点是VS NOT 包含Html.HiddenFor(model=>model.Id)
。
//Create.cshtml
@model MvcMovie.Models.Movie
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Movie</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ReleaseDate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ReleaseDate)
@Html.ValidationMessageFor(model => model.ReleaseDate)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
现在我为类型Movie.cshtml
创建一个名为Movie
的模板化HTML帮助程序编辑器,如下所示。
请注意,为简洁起见,代码已经过简化。重点是VS DOES 包含Html.HiddenFor(model=>model.Id)
。
//Movie.cshtml
@model MvcMovie.Models.Movie
@Html.HiddenFor(model => model.Id)
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ReleaseDate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ReleaseDate)
@Html.ValidationMessageFor(model => model.ReleaseDate)
</div>
如果我使用此模板,我必须按如下方式更改Create.cshtml
:
//Create.cshtml
@model MvcMovie.Models.Movie
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Movie</legend>
@Html.EditorForModel()
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
问题是:
答案 0 :(得分:2)
它添加了隐藏字段,因为它不知道操作的样子。 Action将在url中包含参数ID,因此不需要将其放入隐藏字段。但是在模板中,VS不知道动作是否包含ID,因此它会将隐藏的字段保存为id。