Mar 6, 2014

ViewData and ViewBag in MVC

1. What is ViewData  
2. What is ViewBag  
3. Difference between ViewData and ViewBag 

Both ViewData and ViewBag are used to pass data from a controller to a view. ViewData is a dictionary of objects that are stored and retrieved using strings as keys. The syntax of ViewData is very similar to that of ViewState, SessionState and ApplicationState. 

 // Storing data in ViewData  
ViewData["YourData"] = "SomeData";

// Retrieving data from ViewData  

string strData = ViewData["YourData"].ToString();

ViewData does not provide compile time error checking. For example, if you mis-spell the key names you wouldn't get any compile time error. You get to know about the error only at runtime.

ViewBag uses the dynamic feature that was introduced in to C# 4.0. It allows an object to have properties dynamically added to it. Using ViewBag the above code can be rewritten as below. 

 // Storing data in ViewBag  
ViewBag.YourData = "SomeData"; // Retrieving data from ViewBag string strData = ViewBag.YourData;

Just like 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. Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary.

Please Note: To pass data from controller to a view, It's always a good practice to use strongly typed view models instead of using ViewBag & ViewData. Strongly typed view models  provide compile time error checking. 


Example:

HomeController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCViewBagVsVewData.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
           ViewBag.Countires =new List<string >()
          
           {
            "India",
            "Bangala",
            "Aus",
            "Japan"
           };

           ViewData["Countires"] = new List<string>()
          
           {
            "India1",
            "Bangala1",
            "Aus1",
            "Japan1"
           };

           
           
            return View();
        }

    }
}




Index View:



@{
    ViewBag.Title = "VewBag and ViewData Example";
}

<h2>VewBag   Example</h2>
<ul>
@foreach (string strcountires in ViewBag.Countires)
{
    <li>@strcountires</li>
}

</ul>

<h2>ViewData Example</h2>

 @*casting for view data List<string>)ViewData["Countires"]*@

<ul>
@foreach (string strcountires in (List<string>)ViewData["Countires"])
{
    <li>@strcountires</li>
}

</ul>



Run The application you will get output like:


VewBag Example

  • India1
  • Bangala1
  • Aus1
  • Japan1

ViewData Example

  • India1
  • Bangala1
  • Aus1
  • Japan1



 

No comments:

Post a Comment