Tuesday, 19 November 2013

Pass Data from Controller to View using ViewBag in MVC

Pass Data from Controller to View using ViewBag in MVC

In my last article I explain how to send data from view to controller using ViewData. In this article we will discuss how we can send data using ViewBag. ViewBag used dynamic property which introduced in C# 4.0 and it is typed object which decide type at runtime. This is the reason we didn't get compile time error.

It is actually maintain a dynamic ViewData Dictionary internally so you can say that it’s a wrapper around ViewData.

For example:-

Create a controller name Home and create view name Index.

In this view create a list of type string in which stores the Department Name.

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

namespace MvcApplication5.Controllers
    public class HomeController : Controller
        public ActionResult Index()
            List<string> dept = new List<string>()

            ViewBag.dept_name = dept;
            return View();


In this example we create dynamic property named dept_name.

Now use this ViewBag in View

    Layout = null;

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
        Employee Departments are:-<br />
        @foreach (string dept in ViewBag.dept_name)

As you can see that we need not to perform the type casting while working with ViewBag.

The output of this code is as follows:-

for any query send mail at malhotra.isha3388@gmail.com

1 comment: