Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net-mvc

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?

like image 393
Jim Avatar asked Dec 29 '25 01:12

Jim


1 Answers

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); }
    }
}
like image 124
Chris Pratt Avatar answered Dec 30 '25 15:12

Chris Pratt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!