Practical Approach to Learn MVC: Part 2

Introduction

This article explains MVC in ASP.Net. I will only show the practical (programmatic) approach of learning ASP.Net MVC. In this article I am not paying much attention to the theory.

This is the continuation of Part 1. If you are new to MVC then I will strongly recommend you to please go through part one before proceeding to this article. Click following link for other parts of this tutorial.

In last tutorial we have seen the basic of controller now we will create a View and work with that view in MVC. View is a UI that our end user will see.

For creating a view we have to follow following steps.

Step 1: First assume what we want to display in our controller. In this case we r going to display Employee list in our view for that we create Employee class like follows.

  1. public class Employee  
  2. {  
  3.    public int EmpId { getset; }  
  4.    public string EmpName { getset; }  
  5.    public int EmpSalary { getset; }  
  6. }  
We need following output



Step 2: 
For getting above output we need to pass the list of employees from our controller to view. There are various ways to pass data from controller to view. In this example I am using ViewBag to pass data. I have written following code to pass data from controller to view using ViewBag.
  1. public ActionResult Index()  
  2. {  
  3.    List<Employee> employees = new List<Employee>  
  4.    {  
  5.       new Employee(){EmpId =1,EmpName ="Manish",EmpSalary =30000},  
  6.       new Employee() {EmpId =2,EmpName ="Namit",EmpSalary =20000},  
  7.       new Employee(){EmpId =3,EmpName ="Venkat",EmpSalary =24000},  
  8.       new Employee(){EmpId =4,EmpName ="Sumit",EmpSalary =14000}  
  9.    };  
  10.    ViewBag.Employee = employees;  
  11.    return View();  
  12. }  
Step 3: Now our controller action method is ready so we need to create a view that will collect the list of Employees and render output like above. For adding a view right click anywhere on the controller action method and select add view.



Step 4: Remember view name should be same as the controller action method. So do not change the view name after that select empty(without model) from Template. And click on Add.



Step 5: When you click on add a view has been added to Views folder. Go to View folder that you will find a folder that will match the name of the controller in our case controller name is Default. Click Default folder and expend it then you will find a view Index.cshtml. View name is matching to the controller action method and view folder name is matching to the controller name.



Step 6: Now change the above code of view as I am doing.
  1. @using MVCDemoApps2.Controllers  
  2. @{  
  3.    ViewBag.Title = "Employees List";  
  4. }  
  5.   
  6. <h3>Employees List</h3>  
  7.    <table border="1">  
  8.       <tr>  
  9.          <td style="font-weight :bold">  
  10.             Id  
  11.          </td>  
  12.          <td style="font-weight: bold">  
  13.             Name  
  14.          </td>  
  15.          <td style="font-weight: bold">  
  16.             Salary  
  17.          </td>  
  18.       </tr>  
  19.       @foreach (var Emp in ViewBag.Employee)  
  20.       {  
  21.       <tr>  
  22.          <td>  
  23.             @Emp.EmpId  
  24.          </td>  
  25.          <td>  
  26.             @Emp.EmpName  
  27.          </td>  
  28.          <td >  
  29.             @Emp.EmpSalary  
  30.          </td>  
  31.       </tr>  
  32.       }  
  33.    </table>  
Run the project by pressing Ctrl+F5 u will get above output.

Note:- We use "@" symbol to switch between html and C# code.

There are following ways to pass data from controller to view 
  1. Using ViewBag
  2. Using ViewData["<Name>"]
  3. Using TempData["<Name>"]

Using ViewBag

ViewBag is just a dynamic wrapper around ViewData and exists only in ASP.NET MVC 3. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.

It doesn't require typecasting for complex data types. It also contains a null value when redirection occurs.

Above Index action method is using ViewBag.

  1. Using ViewData["<Name>"]:  
The ViewData is a Dictionary of objects that are derived from the 'ViewDataDictionary' class and it’s having keys as string type and a value for respective keys. It contains a null value on each redirection and it needs typecasting for complex data types.

Example
  1. // Storing data in ViewData  
  2. ViewData["<Name>"] = "SomeData";  
  3. // Retrieving data from ViewData  
  4. string strData = ViewData["<Name>"].ToString();  
  5. Using TempData["<Name>"]:  
TempData by default uses the session to store data, so it is nearly same to session only, but it gets cleared out at the end of the next request. It should only be used when the data needs only to persist between two requests. If the data needs to persist longer than that, we should either repopulate the TempData or use the Session directly.

Example
  1. // Storing data in ViewData  
  2. TempData["<Name>"] = "SomeData";  
  3. // Retrieving data from ViewData  
  4. string strData = TempData["<Name>"].ToString();  
For more details about the difference between ViewBag, ViewData, TempData click here.

We can place our Employee class inside model folder. For accessing that employee class we need to change following thing in our controller action method and View.
  1. //For controller   
  2. using MVCDemoApps2.Models  
  3. // For view  
  4. @using MVCDemoApps2.Models  
The main purpose of Models class is to keep data base connectivity logic. We will discuss it in our next tutorial.

Summary

In this illustration, you came to understand the basics of MVC View and Model.


Similar Articles