In this tutorial, I will show you how to use EditorTemplates in ASP.NET MVC 3.

1. Create the template

In this article, we create the file called “Address.cshtml”. And we place it into “Shared/EditorTemplate/” folder. You can preview it on the image below



2. Create model and controller

Model
: Person Class

public class Person
{
    public Person()
    {
        Name = "George";

        var newYork = new Address
                  {
                      City = "NY",
                      Country = "USA",
                      PostalCode = "10021",
                      Street = "34 Vosges street"
                  };

        var paris = new Address
                        {
                            City = "Paris",
                            Country = "France",
                            PostalCode = "75001",
                            Street = "13 Leclerc street"
                        };

        var bruxelles = new Address
                            {
                                City = "Bruxelles",
                                Country = "Belgium",
                                PostalCode = "65478",
                                Street = "01 Garden Street"
                            };

        Addresses = new List<Address> { newYork, paris, bruxelles };
    }

    public string Name { get; set; }
    public List<Address> Addresses { get; set; }
}

Model : Address Class

public class Address
{
    public string Street { get; set; }
    public string PostalCode { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}


Controler : PersonWithAddress

public class PersonWithAddressController : Controller

{
    public ActionResult Index()
    {
        return View(new Person());
    }
}

3. The View

Here, we strongly typed our View with our model (Person). (Of course it’s not mandatory to use strongly typed view if you want to use EditorTemplate). We want to be able to display the Person with all its addresses.


We call the Html helper EditorFor. For each Address object in the list, Razor will call the Address template.

@model MvcEditorTemplates.Models.Person
@{
    ViewBag.Title = "Person with Addresses";
}
<h2>Person</h2>
<p>
    @Html.LabelFor(model => model.Name)
    @Html.EditorFor(model => model.Name)
</p>   

<h2>Person Addresses</h2>
@Html.EditorFor(model => model.Addresses)

This is the preview