Robert S.
Robert S.

Reputation: 25304

How do I reuse parts of a strongly typed view in Razor?

I'm building a line of business application and when rendering the address, I have this piece of view code, which I really don't want to copy and paste everywhere:

<div class="editor-field">
     @Html.DropDownListFor(model => model.Address.State, new
        SelectList(UsaStates.StateDictionary.OrderBy(s => s.Value), "Key", "Value",
            "Iowa"), "-- Select State --")
     @Html.ValidationMessageFor(model => model.Address.State)
</div>

The Address class is very simple:

public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public int Zip { get; set; }
    public string County { get; set; }
}

The model classes implement the Address like so:

public class Business
{
   // .. other properties
   Address Address {get;set;}
}

public class College
{
   // .. other properties
   Address Address {get;set;}
}

With this, I have two views, Businesses/Create.cshtml and Colleges/Create.cshtml, with their own models.

What is the best way to make this snippet of view code available to all the views in my application whose models have address fields?

Upvotes: 0

Views: 293

Answers (1)

SLaks
SLaks

Reputation: 888283

You should make an editor template.

Upvotes: 1

Related Questions