ehdv
ehdv

Reputation: 4603

Where to put custom object formatter in ASP.NET MVC application?

I'm teaching myself ASP.NET MVC, and am trying to figure out where best to put a function which takes in an Models.Address instance and returns an IHtmlString instance which reads something like:

Line 1<br />
Line 2<br />
City, State

The string could be used in many places throughout my project, so I don't want to write it in one view and have to keep copy-pasting it or attaching that view: By the same logic attaching it to ViewData seems like a bad idea. However, the HtmlEncode method requires an instance of server, which means I can't add the function to the model class either.

Is there a right place to put this - some sort of shared view? (does this belong in the master?) Or am I going about this all wrong?

My current best idea is to create a ViewModel with the method public IHtmlString FormatAddress(Address address, HttpServerUtility server), but I don't know if that's the ASP.NET MVC way to do it.

Upvotes: 0

Views: 222

Answers (2)

Clicktricity
Clicktricity

Reputation: 4209

As this is presentation UI logic, the best place to put it is in a HtmlHelper class.

public static class HtmlHelper
{

   public static HtmlString FormatAddress (this HtmlHelper, Address address)
   {
       string formattedAddress = // the formatted address...

       return HtmlString.Create(formattedAddress);
   }
}

then, from any view you simply call:

<%= Html.FormatAddress(address) %>

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245479

I usually create something like that as an Extension Method on a HelperExtensions class and then place that class in a Helpers folder at the top level of the site.

public static class HelperExtensions
{
    public static Format(this Address address, HttpServerUtility server)
    {
        // Do the work to format here.
    }
}

Upvotes: 2

Related Questions