Monday, 1 June 2015

difference between viewbag and viewdata and tempdata in mvc3

the main difference below,
ViewData:
  • ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys
  • It’s required type casting for complex data type and check for null values to avoid error.

ViewBag: 
  • ViewBag doesn’t require typecasting for complex data type.
  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. 

Check the following example:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var emp = new Employee
        {
            EmpID=101,
            Name = "Deepak",
            Salary = 35000,
            Address = "Delhi"
        };

        ViewData["emp"] = emp;
        ViewBag.Employee = emp;

        return View(); 
    }
}
And the code for View is as follows:
@model MyProject.Models.EmpModel;
@{ 
 Layout = "~/Views/Shared/_Layout.cshtml"; 
 ViewBag.Title = "Welcome to Home Page";
 var viewDataEmployee = ViewData["emp"] as Employee; //need type casting
}
<h2>Welcome to Home Page</h2>
This Year Best Employee is!
<h4>@ViewBag.emp.Name</h4>
<h3>@ViewData.Employee.Name</h3>

No comments:

Post a Comment