Thursday 19 November 2015

ViewData in ASP.net MVC


          We all know that we can't use ViewState in MVC because of Bandwidth Consumption problem. We have several alternatives to maintain state in ASP.net MVC, one of that is ViewData. ViewData is a dictionary; it will pass data between Controller and Views. Controller will add data to the dictionary and view reads from it. So, in this article I'm going to explain how to maintain state over the controls using ViewData with simple example.

 

Using ViewData in ASP.net MVC:

Summary:


          We all know that we can't use ViewState in MVC because of Bandwidth Consumption problem. We have several alternatives to maintain state in ASP.net MVC, one of that is ViewData. ViewData is a dictionary; it will pass data between Controller and Views. Controller will add data to the dictionary and view reads from it. So, in this article I'm going to explain how to maintain state over the controls using ViewData with simple example.

Follow below steps to achieve our goal.


Step 1 : Create Model Class



Create a new class name it as "student" inside Model Folder as follows.
 
 namespace MVCProject.Models  
 {  
   public class Student  
   {  
     public int StudentId { get; set; }  
     public string StudentName { get; set; }  
     public string Group { get; set; }  
   }  
 }  
 

Step 2: Get Model in Controller



Use below namespace as reference.
 
 
 using MVCProject.Models;  
Create new controller or reuse existing controller and Create Student instance and assign the instance to ViewData and return to View. 
 
 public ActionResult GetStudent()  
     {  
       Student objStd = new Student();  
       objStd.StudentId = 1;  
       objStd.StudentName = "Naveen";  
       objStd.Course = "MCA";  
       ViewData["StudentDetails"] = objStd;  
       return View("DemoView");  
     }  
 

Step 3: Display ViewData in Views


Open view and retrieve the Student Data from the ViewData and display it as follows.
 @{  
   Layout = null;  
 }  
 <!DOCTYPE html>  
 <html>  
 <head>  
   <meta name="viewport" content="width=device-width" />  
   <title>DemoView</title>  
 </head>  
 <body>  
   <div>   
     @{  
       MVCProject.Models.Student objStud = (MVCProject.Models.Student)ViewData["StudentDetails"];  
     }  
     <b>Student Details:</b>  
     <br/>  
     Student Id : @objStud.StudentId <br/>  
     Student Name : @objStud.StudentName <br/>  
     Course : @objStud.Course  
   </div>  
 </body>  
 </html>  
 

Result:

Conclusion:



Hope this article will give the brief description about how to handle ViewData in MVC and how to access that ViewData from Controller to View etc..

No comments:

Post a Comment