Thursday, 19 November 2015

ViewBag in ASP.net MVC

           In my Previous post I explained about ViewData to maintain state over MVC Controller, apart from ViewData we have several options to maintain state in ASP.net MVC one of that is ViewBag.

 

Using ViewBag in ASP.net MVC:

Summary:


         In my Previous post I explained about ViewData to maintain state over MVC Controller, apart from ViewData we have several options to maintain state in ASP.net MVC one of that is ViewBag.

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 Course { 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 ViewBag and return to View. 
 
     public ActionResult GetStudent()  
     {  
       Student objStd = new Student();  
       objStd.StudentId = 1;  
       objStd.StudentName = "Naveen";  
       objStd.Course = "MCA";  
       ///ViewData to maintain state  
       //ViewData["StudentDetails"] = objStd;  
       ///ViewBag to maintain state  
       ViewBag.Student = objStd;  
       return View("DemoView");  
     }  
 

Step 3: Display ViewBag in Views



Open view and retrieve the Student Data from the ViewBag 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) ViewBag.Student;  
     }  
     <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 ViewBag in MVC and how to access that ViewBag from Controller to View etc..