In this Session We Will Discuss
ViewBag And ViewData in MVC
Both ViewBag and ViewData is Used to Pass Data From a Controller to a View.Both life lies only in current request.
ViewData is a dictionary object that is derived from System.Web.Mvc.ViewDataDictionary. If u Look the Syantax is very Similar to ViewState,SessionState,ApplicationState.
ViewData["YourKey"]="Some Data"
Here, values can be set using key/value pairs in the controller action method, as shown in the following code snippet:
ViewData["Message"] = “Welcome to our website”; ViewData["ServerTime"] = DateTime.Now;
In the preceding code snippet, two keys, Message and ServerTime, are added with values Welcome to our website and current system date to the ViewData dictionary
You can access the values added in the preceding two keys in a view by using the Razor syntax, as shown in the following code snippet:
The message is: @ViewData["Message"] The Date and Time is: @ViewData ["ServerTime"]
ViewBag is very similar to ViewData. ViewBag is a dynamic property (dynamic keyword which is introduced in .net framework 4.0). ViewBag is able to set and get value dynamically and able to add any number of fields dynamically added to it . ViewBag is just a wrapper around the ViewData.
ViewBag object using a very simple syntax, as shown in the following code snippet:
ViewBag.YourProperty="SomeData"
ViewBag.Message = "Welcome to our website"; ViewBag.ServerTime = DateTime.Now;
In the preceding code snippet, two properties are added in the ViewBag object. The first property, Message, adds a string to it, and the second property, ServerTime, sets the current date and time to it
You can access these two properties in a view by using the Razor syntax, as shown in the following code snippet
The message is: @ViewBag.Message The Date and Time is: @ViewBag.ServerTime
ViewBag is just a dynamic wrapper over the ViewData dictionary. It means that a value saved in the controller action by using ViewBag can also be accessed by using ViewData in a view
For example, the Message property set by using ViewBag in the action method can be accessed by using ViewBag and ViewData in.
Similarities between ViewBag
& ViewData
:
1- Both ViewData, ViewBag does not provide compile time error checking. For example, if you mis-spell the property name, you wouldn't get any compile time error. You get to know about the error only at runtime.
2-Short life means value becomes
null
when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.
Differences between ViewBag
& ViewData
:
- Type Casting is Required in ViewData->
I Have created a controller Named HomeController , In that I have a ActionMethod Named "Index " .Write down the Following Code Here-
public ActionResult Index() { ViewBag.City = new List() { "Lucknow","Kanpur","Jhansi","Mathura" }; }
And The View of the ActionMethod is-
- @foreach (var p in ViewBag.City) {
- @p
If We will use ViewData instead-of ViewBag ,so we need a typecasting of ViewData in Appropriate Datatype .
public ActionResult Index() { ViewData["Message"] = new List() { "Lucknow","Kanpur","Jhansi","Mathura" }; return View(); }
<h2>Data From ViewData</h2>
- @foreach (var p in (List<string>)ViewData["Message"]) {
- @p
}
Passing a Single object Using ViewBag
Step : 1 Create a Class - Go To Solution Explorer > Right Click on Models Folder > Add > New Item > Class ,Write down the Name of Class "Student":
Step 2 : Now Add a Namespace For Access Class of Models Folder in Controller's Action Method "Test ".... or Add Following Code in Home Controller.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcApplication20.Models; namespace MvcApplication20.Controllers { public class HomeController : Controller { public ActionResult Test() { ob = new Student(); ob.ID = 1; ob.Name = "Amit"; ob.Age = 23; ob.Email = "A@gmail.com"; ViewBag.Message = ob; return View(); } }
Step:3 . Now Add a View Page on Test Action Method .Right Click on Test AcionMethod >Go to Add View > and Following Code in View Page.
@{ ViewBag.Title = "Test"; }
Test
Details of Student
@{ var p = ViewBag.Message;
@p.ID @p.Name @p.Age @p.Email
}Passing a List Using ViewBag
Step 1 : Create a ActionMethod on Home Controller Test2:
public ActionResult Test2() { Student ob = new Student(); Student ob2 = new Student(); Student ob3 = new Student(); ob.ID = 1; ob.Name = "Amit"; ob.Age = 23; ob.Email = "A@gmail.com"; ob2.ID = 2; ob2.Name = "Sachin"; ob2.Age = 24; ob2.Email = "S@gmail.com"; ob3.ID = 3; ob3.Name = "Ravi"; ob3.Age = 25; ob3.Email = "R@gmail.com"; var mlist = new List(); mlist.Add(ob); mlist.Add(ob2); mlist.Add(ob3); ViewBag.Message = mlist; return View(); }
After that Create a View Page For The Method..
<table border="1">
@foreach (var p in ViewBag.Message)
{ <tr>
<td>@p.ID</td>
<td>@p.Name</td>
<td>@p.Age</td>
<td>@p.Email</td>
</tr>
}
</table>
Note: To Pass Data From Controller To a View , It's always a good practice to use Strongly Typed View over ViewBag & ViewData .Strongly Typed View Models Provide Compile Time Error Checking.
To Pass a Strong Type Data Create a New Action Method-
public ActionResult Test3()
{
Student ob = new Student();
Student ob2 = new Student();
Student ob3 = new Student();
ob.ID = 1; ob.Name = "Amit"; ob.Age = 23; ob.Email = "A@gmail.com";
ob2.ID = 2; ob2.Name = "Sachin"; ob2.Age = 24; ob2.Email = "S@gmail.com";
ob3.ID = 3; ob3.Name = "Ravi"; ob3.Age = 25; ob3.Email = "R@gmail.com";
var mlist = new List<Student>();
mlist.Add(ob); mlist.Add(ob2); mlist.Add(ob3);
return View(mlist);
}
Now Add a View Page For this Method To Display the Data on the Page.
@model IEnumerable<MvcApplication20.Models.Student>
@{
ViewBag.Title = "Test3";
}
<h2>Test3</h2>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.Email)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
</tr>
}
</table>