Asp.Net MVC View Model


In my previous article we discuss about how to pass simple data from Controller to View using ViewData, ViewBag, and TempData in Asp.Net MVC. Today we discuss about how to pass complex objects from Controller to View using ViewData.

Other than dictionary behaviour of ViewData, it also offers Model property which represents the primary object of the request. ViewData.Model property is conceptually no different from ViewData["Model"], it promotes the model to a first-class citizen and recognizes it as more important than the other data that might be in the request.

Open Microsoft Visual Studio 2013 => Create simple Asp.Net MVC application and save complex object in ViewData.Model as shown below.

using System.Web.Mvc;

 

namespace MVCDisplayData.Controllers

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

 

        public ActionResult Index()

        {

            var objEmp = new Employee { EmpId = "1001", EmpName = "Bob", EmpSal = "$5000" };

 

            return View("Index", objEmp);

        }

    }

 

 

    public class Employee

    {

        public string EmpId { get; set; }

        public string EmpName { get; set; }

        public string EmpSal { get; set; }

    }

}

 

As shown above View() method contains one more property for complex object to pass to View. Access this object in View by using Model property of View and type casting that object into Employee as shown below.

@{

    Layout = null;

} 

<!DOCTYPE html>

 

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

</head>

<body>

    <div>

        @{ var objEmp = (MVCDisplayData.Controllers.Employee)ViewData.Model; }

       

 

        Employee Id: @objEmp.EmpId <br />

        Employee Name: @objEmp.EmpName <br />

        Employee Salary: @objEmp.EmpSal <br />

    </div>

</body>

</html>

 

As shown above we are type casting the ViewData.Model object into Employee. We can avoid type casting by using strongly typed view. Strongly typed view is nothing but binding to single Model. So we can avoid type casting by using strongly typed View and Model as shown below

@model MVCDisplayData.Controllers.Employee

 

@{

    Layout = null;

}

 

<!DOCTYPE html>

 

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

</head>

<body>

    <div>

        Employee Id: @Model.EmpId <br />

        Employee Name: @Model.EmpName <br />

        Employee Salary: @Model.EmpSal <br />

    </div>

</body>

</html>

 

As shown above we avoided the type casting by using strongly typed view.