In ASP.Net MVC Application, mostly we have to send data from the controller to a view, so in this blog we are going to learn about how we can pass data from controller to view.

Passing Data From A Controller To A View In ASP.Net MVC

In an ASP.NET MVC application, a controller typically performs the business logic of the application and needs to return the result to the user through a view.

You can use the following objects to pass data between controller and view:

  1. ViewData
  2. ViewBag
  3. TempData

What Is ViewData ?

  • ViewData passes data from a controller to a view.
  • ViewData is a dictionary of objects that is derived from the ViewDataDictionary class.

Some of the characteristics of ViewData are as follows:

  • The life of a ViewData object exists only during the current request.
  • The value of ViewData becomes null if the request is redirected.
  • ViewData requires typecasting when you use complex data type to avoid error.

The general syntax of ViewData is as follows:

ViewData[“<Key>”] = <Value>;


  • Key: Is a String value to identify the object present in ViewData.
  • Value: Is the object present in ViewData. This object may be a String, object, list, array or a different type, such as int, char, float, double DateTime etc.

Note: ViewData does not provide compile time error checking. For Example- if you mis-spell keys you wouldn’t get any compile time errors. You get to know about the error only at runtime.

Source Code Of HomeController

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

namespace ViewDataDemo.Controllers
    public class HomeController : Controller
        // GET: Home
        public ActionResult Index()
            ViewData["Message"] = "Message from View Data !!";
            ViewData["CurrentTime"] = DateTime.Now.ToLongTimeString();

            string[] Fruits = {"Apple","Banana","Grapes","Orange" };
            ViewData["FruitsArray"] = Fruits;

            ViewData["SportsList"] = new List<string>()
                "Volley Ball"

            Employee Ali = new Employee();
            Ali.EmpID = 11;
            Ali.EmpName = "Ali Khan";
            Ali.EmpDesignation = "Manager";

            ViewData["Employee"] = Ali;

            return View();

Source Code Of Index.cshtml – View

    ViewBag.Title = "Index";


<h2>@ViewData["Message"] </h2>

        foreach (string i in (string[])ViewData["FruitsArray"])

        foreach (string i in (List<string>)ViewData["SportsList"])

    var a = (ViewDataDemo.Models.Employee)ViewData["Employee"];


Click Below Link to Download Notes Of This Blog

Click Below Link to Download Source Code Project Of This Blog

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *