ASP.NET MVC From Beginning - Part Two

In this article, we will discuss controllers, action methods, and data sharing between a Controller to View.

In the first part of this series, we discussed the basics of MVC, features of MVC, and folder structure of MVC. Check the first part of this series to brush up your basics.

Controllers in MVC

 
In MVC, C stands for Controller. Controller is the most important component of MVC which handles the execution of every request. An MVC Controller acts as a mediator between Model and View. Model communicates with the View through Controller and the application execution process always starts from the Controller.

In an MVC application, every Controller is created as a class. A project can have more than one controllers according to our requirement.

Important points to create the Controller

  1. Controller class should be declared with Public Access Modifier.
  2. Controller class name should end with the Controller prefix.
  3. All the Controllers should be inherited from the Controller base class which provides the build in Objects, Methods etc.

In Controller, at the time of processing a request, it will execute the corresponding method which is called Action Method.

 

Action Method in MVC

 
Action method is a Controller method which returns some values as a result. Every request that comes in MVC will be handled by action methods in the Controller. Action method contains the application execution logic to process the request.

Important points about Action Methods

  1. Action method must be Public.
  2. It can’t be static, it must be a non-static method.
  3. Action method returns the View() method. View() is used to process the Views. The View() method is a built-in method in the controller class, at execution time view() execute and result will return from the action method. View() method return type is View Result.
  4. Action method can be parameterized or parameterless.
  5. It can overload but can’t be overridden.

An action method can be defined with various return types

Type of Action Method

  • Action method with view result: These methods return View Page as a result 
  • Action method with the non-view result: Action method that returns data instead of an HTML Page.
  • No action Method
Action Methods 

  • ViewResult
  • Partialviewrestult
  • FileResult
  • JsonResult
  • ContentResult
  • JavascriptResult
  • RedirectResult
  • EmptyResult

ViewResult

It represents a class that is used to render a view whenever the controller action is invoked the view engine dynamically rendered HTML to client

PartialviewResult

It represents a base class that is used to send a partial view to the response. Partial view is a reusable view that is accessible from any view.

JsonResult

It represents a base class that is used to send data in JSON format as a response.

RedirectResult

It controls the processing of application’s action by redirecting to specified URL .

RedirectToRouteResult

It represents a result that performs a redirection by using the specified route values. It can be used to redirect to any controller action within the application.

ContentResult

It represents a user-defined content type that is sent as a response to the client.

JavascriptResult

It represents a base class that sent JavaScript content to response. We can call any Javascript method to sent as a response.

EmptyResult 

It represents a result that returns nothing, so it will not have any return value.

Data Sharing between controller to view

MVC provides different dynamic expression and properties that allow the UI to store values and transport them across multiple tiers. To share data from controller to view, MVC provides different techniques

  • ViewBag
  • ViewData
  • TempData
  • Strongly Typed View 

ViewData

It is a collection object. It stores the data in key-value format.
 
Syntax - Viewdata["key"]=value;

  • Key-string
  • Value-object 
We need to perform typecasting in order to read values from view data because it stores all the values in object format. It is an object of ViewDataDictonary class.

ViewBag

Viewbag is introduced in MVC 3.0. In ViewBag, keys are used as properties. The ViewBag concept is developed in dynamic typing. If we use ViewBag, then there is no need to perform type casting.

Syntax

  1. ViewBag.key=value  
  2. var a =viewBag.key   
ViewBag is also a object of ViewDataDictonary class.

TempData

TempData is the same as viewdata, it stores data in object format, but TempData is available in the current action and redirected action. ViewBag and ViewData scope are available in only one action and view.

Syntax

  1. TempData["Key"]=value;  
  2. var a =(type)TempData["Key"];  

TempData is an object of TempDatadictionary class.

Now, we create an MVC application to use ViewData, ViewBag, and TempData. Let's add an action method into the Welcome controller and add the following lines of code.
  1. public  ActionResult DatashaingExample()  
  2.        {  
  3.            //ViewData Example  
  4.           List<string> cities = new List<string>()  
  5.           {  
  6.               "Jaipur",  
  7.               "Delhi",  
  8.               "Ajmer",  
  9.               "Noida"  
  10.           };  
  11.            //ViewBag Example  
  12.            ViewData["Cities"] = cities;  
  13.            List<string> states = new List<string>()  
  14.            {  
  15.                "Rajasthan",  
  16.                "UP",  
  17.                "Mp",  
  18.                "Punjab"  
  19.   
  20.            };  
  21.            ViewBag.state = states;  
  22.   
  23.            //TempData Example  
  24.            List<string> countries = new List<string>()  
  25.            {  
  26.                "India",  
  27.                "USA",  
  28.                "UK",  
  29.                  
  30.   
  31.            };  
  32.            TempData["Counties"] = countries;  
  33.            return View();  
  34.        }  
Now, right click on action method name and add a View.
 
ASP.NET MVC 
 
In the View, add the following lines of code to display data from Controller.
  1. @{  
  2.     ViewBag.Title = "Data Sharing Example";  
  3. }  
  4.   
  5. <h3 class="btn-primary" style="text-align:center">ViewData Example</h3>  
  6. <ul>  
  7.     @foreach(var city in (List<string>)ViewData["Cities"])  
  8.     {  
  9.         <li>@city</li>  
  10.     }  
  11. </ul>  
  12.   
  13.   
  14. <h3 class="btn-primary" style="text-align:center">ViewBag Example</h3>  
  15. <ul>  
  16.     @foreach (var state in @ViewBag.state)  
  17.     {  
  18.         <li>@state</li>  
  19.     }  
  20. </ul>  
  21.   
  22. <h3 class="btn-primary" style="text-align:center">TempData Example</h3>  
  23. <ul>  
  24.     @foreach (var country in (List<string>)TempData["Counties"])  
  25.     {  
  26.         <li>@country</li>  
  27.     }  
  28. </ul>  

Run the project and check result.

ASP.NET MVC 

Strongly typed views

When a View is designed by targeting a specific class, then that View is called Strongly-typed View. In a Strongly-typed View, the View is bound with corresponding model class.

Advantages of using Strongly-typed View

  • It supports intelligence
  • Not need to perform type casting
  • Make database related operations easy.
To create a Strongly-typed View, first, go to the model folder and add a class. Now, rename it as Employeedetails.cs.
  1. public class Employeedetails  
  2.  {  
  3.      public  int Id { getset; }  
  4.      public string EmployeeName { getset; }  
  5.      public string City { getset; }  
  6.      public string Departmnet { getset; }  
  7.   
  8.  }  
Now, add an action method in the Welcome controller, name it as Empdetails, and create a list and add some data in it.
  1. public ActionResult EmpDetails()  
  2. {  
  3.     List<Employeedetails> ED = new List<Employeedetails>();
  4.     Employeedetails ED1 = new Employeedetails()  
  5.     {
  6.         Id = 1,  
  7.         EmployeeName = "Sanwar",  
  8.         City = "Jaipur",  
  9.         Departmnet = "IT"  
  10.     };  
  11.   
  12.     Employeedetails ED2 = new Employeedetails()  
  13.     {
  14.         Id = 2,  
  15.         EmployeeName = "John",  
  16.         City = "Jaipur",  
  17.         Departmnet = "IT"  
  18.     };  
  19.     ED.Add(ED1);  
  20.     ED.Add(ED2);  
  21.   
  22.     return View(ED);  
  23.   
  24. }  
Now, right click on the action method and add a View and select the following.
  • View Name: EmpDetails 
  • Template: Empty 
  •  Model class: Employeedetails
ASP.NET MVC 
 
Add a table in View and display the data. Add the following code in View.
  1. @using MvcPartOne.Models;  
  2. @model List<Employeedetails>  
  3. @{  
  4.     ViewBag.Title = "EmpDetails";  
  5. }  
  6.   
  7. <h2 class="btn-primary" style="text-align:center">Employee Details</h2>  
  8. <table class="table table-responsive">  
  9.     <tr>  
  10.         <th>Id</th>  
  11.         <th>EmployeeName</th>  
  12.         <th>City</th>  
  13.         <th>Department</th>  
  14.     </tr>  
  15.     @foreach (Employeedetails item in Model)  
  16.     {  
  17.     <tr>  
  18.         <td>  
  19.             @item.Id  
  20.         </td>  
  21.         <td>  
  22.             @item.EmployeeName  
  23.         </td>  
  24.         <td>  
  25.             @item.City  
  26.         </td>  
  27.         <td>  
  28.             @item.Departmnet  
  29.         </td>  
  30.     </tr>  
  31.     }  
  32. </table>  
Now, run the project and check the result.
 
ASP.NET MVC 
 
Summary
 
In this article, we learned about Controllers, Action Methods, and data sharing methods between Controller to View in MVC. In the next part of the series, we will discuss models and basics of Entity Framework.