Pergunta

I work with MVC and has one question, what is the best practice for building concatenated View Model properties? I can build concatenated field(FullName) in two places:

  1. In Model View like this

     public class User
        {
           public string FirstName { get; set; }
           public string LastName { get; set; }
           public string FullName { get {return FirstName+LastName;} }  
        }
    
    
    public ActionResult Users()
    {
     var model = new User
                 {
                    FirstName = "Tomas",   
                    LastName = "Saint",     
                  });
    
     return View(model);
    }
    
  2. In Controller

    public class User
    {
       public string FullName { get; set; }
    }
    
    
    public ActionResult Users()
    {
     var model = new User
                 {
            FullName = "Tomas" + "Saint";   
                  });
    
     return View(model);
    }
    
Foi útil?

Solução

If the calculations/functions are associated with formatting for the view then i would go ahead and put the functionality in the view model, like your full name property this is correct in the view model. However if you have any functions/calculations that require domain logic, then i dont think view models are the place for that and that can reside either in the domain model for reusability, or somewhere where else in your business logic layer.

So the short answer - formatting for the view in view models, any domain logic elsewhere.

Outras dicas

Any methods or properties that calculate values for display purposes (like FullName in your example) belong in the ViewModel. Doing that gives you a clean, type-safe means of passing the data to the view and allows the view to access the property in a consistent way. This approach also has the advantage of making the property available wherever that particular ViewModel is used. That will not be the case if you add the property to your controller.

Example below using Razor syntax:

@model MvcApplication.Models.User
...
<div class="editor-label">
    @Html.LabelFor(m => m.FullName)
</div>
<div class="editor-field">
    @Html.DisplayFor(m => m.FullName)
</div>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top