Search code examples
asp.net-mvcasp.net-mvc-viewmodel

ViewModel or View responsibility in draw logic


Yesterday I had a little discussion with one of my work partners about ViewModel and View responsibility. I have a text that changes in different contexts, like Edit/New mode in the View. One of the team programmers wrote somthing like this:

@if (Model.IsNew)
{
    @Resources.New;
}
else
{
    @(Resources.Editing + " " + Model.Name);
}

I defend that this logic is ViewModel responsibility:

In the ViewModel:

public string PageTitle => IsNew ? Resources.New : $"{Resources.Editing} {Name}";

Then in the View:

<h2>
    @Model.PageTitle
</h2>

But my colleage defends who that is a print logic, so the View has the responsibility.

Both of us have our arguments, but I would like to know the community opinion.


Solution

  • If you look up the definiton of MVC pattern, you can see that:

    A view generates new output to the user based on changes in the model.

    Means that if you want to adhere to the Separation of Concerns principle properly, the view is responsible for displaying the data in the UI, the model stands for as a property bag of data you will bring to view.

    So basically the underlying model of your view is your viewmodel, and by this I would put this property into the viewmodel and the logic that sets it to the controller/viewmodel builder/service/whatever fits your needs.

    To further defend this, ask your collegue how easy would that be to unit/integaration test the code in the view? Bringing a new test just for asserting a the outcome this logic? Brings no real business value to me...

    To extend this subject further to keep the concerns separated you could:

    • Create very thin and focused controllers for modes, such as new, edit, etc.
    • Separate viewmodels per these modes, so your viewmodels are in 1-1 relations to views.

    Although all these are opinionated, make sure to create an environment that fits everyone.