Tuesday, 26 May 2015

Passing Data from Controller to View in ASP.NET MVC

In ASP.Net MVC, We can pass data from the controller to corresponding view using ViewData and ViewBag. We can also pass data from the View to Controller using Post/ QueryString/ HiddenField and We can pass data from Controller to Controller using TempData.

In this post, we will learn How to Pass Data from Controller to View in ASP.NET MVC using ViewData and ViewBag. In the previous post, we saw How to Pass parameter or Query String in Action Method in ASP.NET MVC.

1. ViewData:
ViewData is a dictionary object used to pass data between from the controller to view in the form of Key-Value pair. ViewData is derivative of the ViewDataDictionary class. ViewData is introduced in MVC 1.0. ViewData requires type casting for complex data types and if redirection occurs, its value becomes NULL.

Example of ViewData: 
Create a New Empty ASP.Net MVC Project and Add a Controller named as HomeController in it.
Store the current DateTime in ViewData object and return a View. Now add a View(named as Index).
public ActionResult Index()
{
      ViewData["DateTime"] = DateTime.Now;
      return View();
}

Now call the ViewData["DateTime"] object in View using @ symbol because we have selected the Razor View Engine.
Index.cshtml Code:
@{
    ViewBag.Title = "Index";
}

<h2>ViewData Example</h2>
<p>@ViewData["DateTime"]</p>
Preview:

2. ViewBag:
ViewBag is a dynamic property(a new C# 4.0 feature) which means it has no pre-defined properties. ViewBag is a wrapper around the ViewData that exposes the ViewData dictionary as a dynamic object. ViewBag is slower than ViewData and it does not require any type of typecasting for the complex data type. Visual Studio cannot provide Intellisense support for the dynamic objects so error not shown at the design time.

Example of ViewBag:
Inside HomeController, Add another Action Method(named it as Demo). Store the current DateTime in ViewBag.DateTime dynamic object and return a View.
public ActionResult Demo()
{
       ViewBag.DateTime = DateTime.Now;
return View();
}
Now add a View(named as Demo).
Demo.cshtml Code:
@{
    ViewBag.Title = "Index";
}

<h2>ViewData Example</h2>
<p>@ViewData["DateTime"]</p>
Preview:
Hope you like it. Thanks.
[Download Source Code via Google Drive]

0 comments:

Post a Comment

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Subscribe us on YouTube

Like us on Facebook

Follow us on Google+