April 3, 2010
With the new various For methods in MVC (DisplayFor, TextBoxFor, etc.), these methods use a lambda to specify the fields to display/render. The following form below:
<% Html.BeginForm(); %>
<%= Html.ValidationSummary(“The following errors have occurred:”) %>
<%= Html.Hidden(“Story.ProjectPhaseKey”, this.Request.QueryString.Get(“phase”)) %>
<%= Html.Hidden(“Story.ProjectKey”, this.RouteData.Values[“id”])%>
<div>
<span>Title</span>
<span>
<%= Html.TextBoxFor(i => i.Story.Title) %>
</span>
</div>
<div>
<span>Description</span>
<span>
<%= Html.TextAreaFor(i => i.Story.Description) %>
</span>
</div>
<div>
<input type=”submit” value=”Save Changes” />
</div>
<% Html.EndForm(); %>
Renders the following:
<input id=”Story_ProjectPhaseKey” name=”Story.ProjectPhaseKey” type=”hidden” value=”2″ />
<input id=”Story_ProjectKey” name=”Story.ProjectKey” type=”hidden” value=”1″ />
<div>
<span>Title</span>
<span>
<input id=”Story_Title” name=”Story.Title” type=”text” value=”” />
</span>
</div>
<div>
<span>Description</span>
<span>
<textarea cols=”20″ id=”Story_Description” name=”Story.Description” rows=”2″></textarea>
</span>
</div>
<div>
<input type=”submit” value=”Save Changes” />
</div>
Notice how the ID’s use the identifier in the lambda; the i.Story.Description lambda expression evaluates to Story_Description and Story.Description, as a means to automatically populate the data for model binding.