29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

properties for the Address type.<br />

Listing 24-12. Updating the CreatePerson.cshtml File<br />

@model MvcModels.Models.Person<br />

@{<br />

ViewBag.Title = "CreatePerson";<br />

Layout = "∼/Views/Shared/_Layout.cshtml";<br />

}<br />

Create Person<br />

@using(Html.BeginForm()) {<br />

@Html.LabelFor(m => m.PersonId)@Html.EditorFor(m=>m.PersonId)<br />

<br />

@Html.LabelFor(m => m.FirstName)@Html.EditorFor(m=>m.FirstName)<br />

<br />

@Html.LabelFor(m => m.LastName)@Html.EditorFor(m=>m.LastName)<br />

<br />

@Html.LabelFor(m => m.Role)@Html.EditorFor(m=>m.Role)<br />

<br />

@Html.LabelFor(m => m.HomeAddress.City)<br />

@Html.EditorFor(m=> m.HomeAddress.City)<br />

<br />

<br />

@Html.LabelFor(m => m.HomeAddress.Country)<br />

@Html.EditorFor(m=> m.HomeAddress.Country)<br />

<br />

Submit<br />

}<br />

I have used the strongly typed EditorFor helper method, and specified the properties I want to edit from the<br />

HomeAddress property. The helper automatically sets the name attributes of the input elements to match the format that<br />

the default model binder uses, as follows:<br />

...<br />

<br />

...<br />

As a consequence of this feature, I don’t have to take any special action to ensure that the model binder can create the<br />

Address object for the HomeAddress property. I can demonstrate this by editing the<br />

/Views/Home/Index.cshtml view to display the HomeAddress properties when they are submitted from the<br />

form, as shown in Listing 24-13.<br />

Listing 24-13. Displaying the HomeAddress.City and HomeAddress.Country Properties in the Index.cshtml File<br />

@model MvcModels.Models.Person<br />

@{<br />

ViewBag.Title = "Index";<br />

Layout = "∼/Views/Shared/_Layout.cshtml";<br />

}<br />

Person<br />

ID:@Html.DisplayFor(m => m.PersonId)<br />

First Name:@Html.DisplayFor(m => m.FirstName)<br />

Last Name:@Html.DisplayFor(m => m.LastName)<br />

643

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!