3

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?

4

2 回答 2

3

对于一次性,我会说使用视图模型。如果它是您将反复重用的东西,请将其移动到您的视图/视图模型/等的实用程序类中。可以参考。

而且,从技术上讲,两种方式都没有错。将该方法放在一个实用程序类中,然后将一个属性添加到您的视图模型以返回它,例如:

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

    public string USFormattedTaxID
    {
        get { return Utilities.FormatTaxID(TaxID); }
    }
}
于 2013-10-02T20:36:31.090 回答
1

公司本地化到公司上下文的 TaxID 完全是公司的财产,而不是演示详细信息。

于 2013-10-02T20:41:06.617 回答