2011-02-16 47 views
0

如果VS为[HttpGet] Create创建了一个强类型视图,那么我将按如下方式获取该模型的标记。我可以删除Html.HiddenFor(model => model.Id),该应用程序仍然有效。它是为了什么?

请注意,为简洁起见,代码已被简化。重要的一点是,VS确实是不是包括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> 
} 

现在我创建模板HTML辅助编辑器类型Movie命名Movie.cshtml如下。

请注意,为简洁起见,代码已被简化。重要的一点是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. 由于隐藏字段的形式可以在没有任何被删除副作用,在这种情况下,什么是隐藏领域?

回答

2

它增加了隐藏字段,因为它不知道动作是怎么样的。 Action将在url中包含参数ID,因此不需要将其放入隐藏字段中。然而,在模板中,VS不知道动作是否包含ID,所以它放置了隐藏的字段,以确保id。

相关问题