Access List Value from ViewData in MVC

Let’s create a MVC application and name it MVCDemo.

Let’s create a model and name it StudentModel.

  1. public class StudentModel  
  2. {  
  3.        
  4.    public int StudentId { getset; }  
  5.   
  6.    public string Name { getset; }  
  7.   
  8.    public bool IsRequired { getset; }  
  9.   
  10.    public string Address { getset; }  
  11.   
  12.    public string City { getset; }  
  13.   
  14. }  
In HomeController.cs
  1. public ActionResult HtmlView()  
  2. {  
  3. List<StudentModel> objSt = new List<StudentModel>();  
  4. StudentModel s = new StudentModel();  
  5.        s.Name = "Pramod";  
  6.        s.IsRequired = false;  
  7.        s.Address = "Shalimar Garden";  
  8.        s.City = "Ghaziabad";  
  9.        objSt.Add(s);  
  10.   
  11.        StudentModel s1 = new StudentModel();  
  12.        s1.Name = "Anuj";  
  13.        s1.IsRequired = true;  
  14.        s1.Address = "New Delhi";  
  15.        s1.City = "New Delhi";  
  16.        objSt.Add(s1);  
  17.        ViewData["Data"] = objSt;  
  18. return View();  
  19. }  
Let’s add a view and name it HtmlView.
  1. @using MvcDemo.Models;  
  2. @{  
  3.     ViewBag.Title = "HtmlView";  
  4. }  
  5.   
  6. <h2 style="font-family:Verdana;">HtmlView</h2>  
  7. <div style="font-family:Verdana; font-size:13px; border:dashed 1px black; width:350px;">  
  8. <table>  
  9.     <tr>  
  10.         <td style="font-family:Verdana; font-size:14px; font-weight:bold;">Name</td>  
  11.         <td style="font-family:Verdana; font-size:14px; font-weight:bold;">Address</td>  
  12.     </tr>  
  13.     @{  
  14.         if(ViewData["Data"]!=null)     
  15.         {  
  16.             if(ViewData.Values !=null && ViewData.Values.Count()>0)  
  17.             {  
  18.                 foreach (var item in ViewData["Data"] as List<StudentModel>)  
  19.                 {  
  20.                     <tr>  
  21.                         <td style="font-family:Verdana; font-size:12px;">@item.Name</td>  
  22.                         <td style="font-family:Verdana; font-size:12px;">@item.Address</td>  
  23.                     </tr>  
  24.                 }  
  25.             }  
  26.         }  
  27.      }  
  28. </table>  
  29. </div>  
Press F5 and run the application and see the output.

Output

html view

I hope you enjoy this article.
Happy coding.

Next Recommended Reading ViewData VS ViewBag Vs TempData in MVC