Showing posts with label viewdata in mvc. Show all posts
Showing posts with label viewdata in mvc. Show all posts

Tuesday, 19 November 2013

Pass data from Controller to View using ViewData in MVC

Pass data from Controller to View using ViewData in MVC

ViewData is used to access data from controller to view. ViewData stores data as key-value format. ViewData type is  ViewDataDictionary. Internal declaration of ViewData is:-

public ViewDataDictionary ViewData { get; set; }

Syntax of ViewData

ViewData[“key”]=value;

ViewData is dictionary type which stores data in object format.  So we need to perform type casting at the time of data retrieval.

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>()
            {"HR","Sales","Developer"};

            ViewData["dept_name"] = dept;
            return View();
        }

    }
}