Jim
Jim

Reputation: 2300

Do formatting helper methods belong in the model, the view model, or a separate class?

I have a model that stores company information, including tax IDs. In the US, these are 9 digit numbers and are typically displayed as ##-#######. However, in my system, I am storing these as strings with no hyphen - since other countries can have identification numbers that differ in length and format, I don't want be limited to a US standard.

Now I want to program my views to display US tax IDs in their "friendly" format. I have this working right now with a helper method I put in the Company model class:

public string FormatTaxID(string TaxID)
{
    if (Address.Country == "United States")
        return Regex.Replace(TaxID, @"(\d{2})(\d{7})", "$1-$2");
    else
        return TaxID;
}

Then in my view, I'm using:

@item.FormatTaxID(item.TaxID)

This all works fine, but it doesn't feel right to store a method like this in the model - it feels like this is more of a view/view model responsibility than a model responsibility, as it is solely for presentation.

I am using view models and thought of putting it there, but I I have multiple view models for the underlying model and don't want to repeat code if I don't have to. Also, my view model for the index uses collections and I'm not sure how I would work the method into it:

public class CompanyIndexViewModel
{
    public IEnumerable<Company> Companies { get; set; }
    public IEnumerable<Document> Documents { get; set; }
}

How would I apply this method to a collection like that?

Another option is creating a new helper/utility class and sticking it in there. What would MVC convention dictate?

Upvotes: 3

Views: 1009

Answers (2)

Tetsujin no Oni
Tetsujin no Oni

Reputation: 7375

The localized-to-the-Company-context TaxID of the company is properly a property of the Company, and is not a presentation detail.

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239430

For one-offs, I'd say use the view model. If it's something that you will reuse over and over, move it into a utility class that your views/view models/etc. can reference.

And, there's technically nothing wrong sort of doing it both ways. Put the method in a utility class and then add a property to your view model that returns this, e.g.:

public class CompanyIndexViewModel
{
    ...
    public string TaxID { get; set; }

    public string USFormattedTaxID
    {
        get { return Utilities.FormatTaxID(TaxID); }
    }
}

Upvotes: 3

Related Questions