Search code examples
c#asp.net-mvcrazor

MVC ViewModel Class


I am using C# MVC with Razor.

Say if I have a view that shows a list, drop down, and 2 text boxes. Should all of this information be kept in 1 class which will then be pass to my view?


Solution

  • I can't stress enough the importance of using ViewModels for passing data from your controllers to the view. As stated in your question, you're doing this already which is an excellent start!

    So .. this is how I would do it.

    public class IndexViewModel // or DetailsViewModel or whatever the Action Method is
    {
        public IEnumerable<Foo> Foos { get; set; }
        public SelectList DropDownBox { get; set; }
        public string Name { get; set; } // Textbox 1
        public string Description { get; set; } // Textbox 2
    }
    

    OK. so lets see what I've done.

    I've passed all the information which the View requires. Nothing more, nothing less. Just the -exact- info.

    The Foos are a list of foo which you can then loop through to render. (PRO TIP: Use DisplayTemplates to render out your custom type / collections of custom types).

    I've also suggested in passing in a SelectList which is the drop down contents, etc. Some people don't like this (which is fine). Instead they pass in a collection of their items to render in the drop down list, but i personally find that far too leaky. The key reason why we have ViewModels is so we can test these things.

    Finally, I have a single property per text box.

    So in summary, I put all the information in a single ViewModel. This view model could contain other classes (exposed via properties). But yes - you want one ViewModel per view.