0

I'm learning about ASP.NET and working in an application and I don't seem to understand the difference between the Model and the ViewModel. When in a View the information you want is taken from the Model you call using @model. If you want to make a dropdown list you will display the information you get from there right? When using @Html.Action you call a method of the Controller where you create a ViewModel object with the same {get; set} methods and the same information as the Model. So why using this if it's the same as the Model? Or it isn't?

Probably my question doesn't make 100% sense, keep in mind I'm still new to ASP.NET. What I need to understand is the difference between the Model and the ViewModel.

I found this post: ASP.NET MVC Model vs ViewModel, but I need the answer to be more specific.

Community
  • 1
  • 1

1 Answers1

1

Let's say that you have 2 models Blog and Category:

public class Blog
{
    public string BlogTitle{ get; set; }
    public string Body{ get; set; }
}

public class Category
{
    public string CategoryTitle{ get; set; }
}

A ViewModel is a solution for showing both of these on a single view. It is an alternative to using ViewBag, but in my opinion a much better one, because it allows you to strongly type the model properties.

In this case if you wanted to show a Blog post and list of categories you would create a view model

public class BlogCategoriesViewModel
{
    public Blog Blog { get; set; }

    public IEnumerable<Category> Categories { get; set; }

}

And in your view:

@model Project.ViewModels.BlogCategoriesViewModel

<h1>@Model.Blog.BlogTitle</h1>

<h2>Categories</h2>
@foreach (var item in Model.Categories) 
{
    <p>item.CategoryTitle</p>
}

In the View the ViewModel in this case is basically a collection of 2 submodes. A ViewModel also lets you add properties to your view which aren't directly mapped to domain entities.

Hope that helps

Evonet
  • 3,600
  • 4
  • 37
  • 83