1.2.4.ViewModel

  • Why need ViewModel?

    • It's a model specifically built for a view

  • To establish multiple model's relation, we can use ViewModel to do that

    • 1.Create a folder which is called ViewModel

    • 2.Create a ViewModel class which contains models

            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Web;
            using Vidly2.Models;
            namespace Vidly2.ViewModels
            {
                public class RandomMovieViewModel
                {
                    public Movie Movie { get; set; }
                    public List<Customer> Customers { get; set; }
                }
            }
    • 3.Modify controller

        using System.Web;
        using System.Web.Mvc;
        using Vidly2.Models;
        using Vidly2.ViewModels;
        namespace Vidly2.Controllers
        {
            public class MoviesController : Controller
            {

                // GET: Movies/Random
                public ActionResult Random()
                {
                    var movie = new Movie() { Name = "Shrek" };
                    var customers = new List<Customer>
                    {
                        new Customer {Name = "Customer 1"},
                        new Customer {Name = "Customer 2"}
                    };

                    var viewModel = new RandomMovieViewModel
                    {
                        Movie = movie,
                        Customers = customers
                    };

                    return View(viewModel);
                }
            }
        }
  • 4.Modify View

@model Vidly2.ViewModels.RandomMovieViewModel
    @{
        ViewBag.Title = "Random";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }

h2@Model.Movie.Name/h2

Last updated