我可以删除Html.HiddenFor(model => model.Id),应用程序仍然有效。它是为了什么?

时间:2011-02-16 08:48:01

标签: asp.net-mvc asp.net-mvc-3

如果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>
}

问题是:

  1. 由于可以删除隐藏的字段表单而没有任何副作用,在这种情况下,隐藏字段是什么?

1 个答案:

答案 0 :(得分:2)

它添加了隐藏字段,因为它不知道操作的样子。 Action将在url中包含参数ID,因此不需要将其放入隐藏字段。但是在模板中,VS不知道动作是否包含ID,因此它会将隐藏的字段保存为id。