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();
        }

    }
}



Now use this ViewData in your View in the following manner:-

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        Employee Departments are:-<br />
        @foreach (string dept in (List<string>) ViewData["dept_name"])
        {
       
            <p><b>@dept</b></p>
       
        }
    </div>
</body>
</html>

As you can see that to traverse this ViewData I have to perform the type casting.
The output of this code is as follows:-



Figure 1

For any query send mail at info@techaltum.com


2 comments:

  1. There are few points should be taken into consideration while using viewdata
    1. ViewData should be used for temp objects like error messages or so. For a object like deptList a property in Model class must be made and model should be passed to view and the deptList hould be accessed by Model Object. However in case your view is not bound to a perticular
    Model (i.e loosely typed model), This approach is ok. But in case of strongly typed view this approach should be avoided.

    ReplyDelete
    Replies
    1. Thanks for your appreciation and suggestion. i didn't discuss model till now in this tutorial. when i will discuss about model then i will publish my article on Strongly View.

      Delete