Tuesday, January 25, 2011

Prefixing Input Elements Of Partial Views With ASP.NET MVC

Suppose we have the following set of classes in an ASP.NET MVC project:

public class NameModel
{
 [Display(Name = "First name")]
 [Required]
 public string FirstName { get; set; }
 [Display(Name = "Last name")]
 [Required]
 public string LastName { get; set; }
}

public class AddressModel
{
 [Required]
 public string Street { get; set; }
 [Required]
 public int Number { get; set; }
 [Display(Name = "Zip code")]
 [Required]
 public int ZipCode { get; set; }
 [Required]
 public string City { get; set; }
}
public class PersonModel
{
 public PersonModel()
 {
   Name = new NameModel();
   Address = new AddressModel();
 }
 public NameModel Name { get; private set; }
 public AddressModel Address { get; private set; }

 [Required]
 [MustBeValidEmailAddress(ErrorMessage = "Not a valid email")]
 public string Email { get; set; }
}

An input form for an instance of PersonModel could look like this:

@using (Html.BeginForm("MyPostAction", "MyController", FormMethod.Post))
{
   @Html.ValidationSummary(true)
   <p>
       @Html.LabelFor(model => model.Name.FirstName)<br />
       @Html.TextBoxFor(model => model.Name.FirstName)
       @Html.ValidationMessageFor(model => model.Name.FirstName)
   </p>
   <p>
       @Html.LabelFor(model => model.Name.LastName)<br />
       @Html.TextBoxFor(model => model.Name.LastName)
       @Html.ValidationMessageFor(model => model.Name.LastName)
   </p>
   <p>
       @Html.LabelFor(model => model.Address.Street)<br />
       @Html.TextBoxFor(model => model.Address.Street)
       @Html.ValidationMessageFor(model => model.Address.Street)
   </p>
   <p>
       @Html.LabelFor(model => model.Address.Number)<br />
       @Html.TextBoxFor(model => model.Address.Number)
       @Html.ValidationMessageFor(model => model.Address.Number)
   </p>
   <p>
       @Html.LabelFor(model => model.Address.City)<br />

Read more:  The Inquisitive Coder - Davy Brion's Blog