Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does formatting logic belong with MVC?

Say my phone number is stored in the database as a 10-digit string:

0000000000

And I want to format this phone number when presenting it to the user as:

(000) 000-0000

And I have an extension method in a utility assembly that handles this formatting:

static string ToPhoneNumber(this string value)
{
    return Regex.Replace(value, @"(\d{3})(\d{3})(\d{4})", "($1) $2-$3");
}

My question is, at what point do I apply this conversion?

1) In the view:

@Model.PhoneNumber.ToPhoneNumber()

2) In the view model:

public string FormattedPhoneNumber
{
    get
    {
        return this.PhoneNumber.ToPhoneNumber()
    }
}

3) In the controller:

userModel.FormattedPhoneNumber = userModel.PhoneNumber.ToPhoneNumber()

4) In the domain model (same implementation as #2)

5) In the service (same implementation as #3)

Also, does the answer depend whether it's a global formatting need (like phone number) vs. an isolated one-time formatting on a single view?

I would give my thoughts, but don't want to influence any answers.

like image 501
Jerad Rose Avatar asked Feb 14 '13 15:02

Jerad Rose


2 Answers

I personally like to keep things in my ViewModel because what you end up with is strange looking code in your view if you don't. Let's take your example.

Razor View:

@using MyNamespace.Models.Extensions
@model MyNamespace.Models.ViewModels.IndexViewModel

@if (string.IsNullOrWhiteSpace(Model.PhoneNumber) {
   <div> @Model.PhoneNumber.ToPhoneNumber() </div>  
}

Versus the alternative:

Razor View:

@model MyNamespace.Models.ViewModels.IndexViewModel

@Model.FormattedPhoneNumber

ViewModel :

 public string FormattedPhoneNumber {
     get {
         return PhoneNumber.IsEmpty()
         ? "Not Available"
         : PhoneNumber.ToPhoneNumber();
     }
 }

You could definitely improve my code, but the point is that it keeps your views simpler and lest cluttered with branching logic.

Also, I never claimed to be a saint, so I don't always follow my own advice, but I should. Do as I say, not as I do :)

like image 71
Khalid Abuhakmeh Avatar answered Oct 05 '22 07:10

Khalid Abuhakmeh


I think it is view responsibility to decide how to display data. Because only the view knows what is available for presentation. On the other hand it is probably easier to do it in controller. And controller would know about locale of the user. Over all I think it makes very little difference.

like image 45
kos Avatar answered Oct 05 '22 06:10

kos