ViewData
- It is used to pass data from controller to view.
- Data is available only for the current request and it's value becomes null once redirection occurs.
- Derived from ViewDataDictionary class.
- It requires typecasting for complex data type and checks for null values to avoid error.
ViewBag
- It is also used to pass data from controller to view.
- Data is available only for the current request and it's value becomes null once redirection occurs.
- It does not required typecasting.
- It is a dynamic property that takes advantage of the new dynamic features in C# 4.0
Example of ViewBag & ViewData
Step 1 : Create new MVC Project
Step 2 : Change the Name, Location of Project
Step 3 : Choose Empty MVC Application
Step 4 : Create Controller
Step 5 : Put the given Code in Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCExample.Controllers
{
public class HomeController : Controller
{
//
// GET:
/Home/
public ActionResult Index()
{
ViewBag.Sports = new List<String>()
{
"Cricket",
"Football",
"Volleyball",
"Basetball"
};
return View(ViewBag);
}
public ActionResult UsingViewData()
{
ViewData["Sports"] = new List<String>()
{
"Cricket",
"Football",
"Volleyball",
"Basetball"
};
return View(ViewData);
}
}
}
Step 6 : Right click index, UsingViewData method of return type ActionResult to add two views. One for ViewBag and other for ViewData.
Step 7 : Index view will be created in Home Folder inside Views Folder.
Put the following code in View
In Index.cshtml
@{
ViewBag.Title = "Sports";
}
<h2>Sports</h2>
<ol>
@foreach (string strSports in ViewBag.Sports)
{
<li>
@strSports
</li>
}
</ol>
In UsingViewData.cshtml
@{
ViewBag.Title = "UsingViewData";
}
<h2>Sports with ViewData</h2>
<ol>
@foreach (string strSports in (List<String>)ViewData["Sports"])
{
<li>
@strSports
</li>
}
</ol>
Step 8 : Run the Application
0 comments:
Post a Comment