Questions tagged [viewdata]

ViewData is a dictionary used in C# MVC to pass data from the controller to the view. This feature was first introduced in MVC 1.0. To use this tag, the post must be using C#, MVC, and must be in regards to the use of ViewData.

ViewData is one of the alternate ways to pass data from controller to view without using the Model.

Syntax

ViewData is a dictionary that is set in the controller and is read in the view. For example:

Controller

public ActionResult ViewTest()
{
    ViewData["Content"] = "some text";
    return View();
}

View

<div>
    ViewData content: @ViewData["Content"]
</div>

Result

<div>
    ViewData content: some text
</div>

ViewData only accepts string as keys, otherwise it will generate an error alert. So the following is not possible:

ViewData[1] = "some text"; //cannot convert from 'int' to 'string'

As far as a value, these are totally legal:

ViewData["Content"] = 1;            //prints 1
ViewData["Content"] = true;         //prints True
ViewData["Content"] = DateTime.Now; //prints the date (i.e. 4/16/2019 9:50:05 AM)

If the value is a object, you must cast the ViewData in the view in order to access the property to read from:

Controller

public ActionResult ViewTest()
{
    ViewData["Content"] = new SomeClass
    {
        SomeProp = "some text"
    };
    return View();
}

View

<div>
    @{
        var viewDataContent = (SomeClass) ViewData["Content"];
    }
    ViewData content: @viewDataContent.SomeProp
</div>

Because you must cast an object, you cannot use an anonymous type as a value. While a workaround is possible, it's not recommended as it results in ugly code that is difficult to maintain.

Life

The life of ViewData is only for the current request. Once the request is done, ViewData expires. This means that if ViewData is set before a redirect, it will be expired by the time you get to the view:

Controller

public ActionResult ViewRedirect()
{
    ViewData["Content"] = "some text";
    return RedirectToAction("ViewTest");
}

public ActionResult ViewTest()
{
    return View(); // ViewData["Content"] expires
}

View

<div>
    ViewData content: @ViewData["Content"]
</div>

Result

<div>
    ViewData content:
</div>

References

321 questions
2
votes
1 answer

How to pass information from controller to viewdata? asp net mvc c#

I am building a pagination my mvc project and have follew problem. I did everything for pagination and now need just pass a page information to view data in view. I have a user control Pagination: Pagination.ascx: <%@ Control Language="C#"…
r.r
  • 7,023
  • 28
  • 87
  • 129
2
votes
1 answer

The new ViewModel doesn't obsolete the ViewModel pattern in ASP.NET MVC 3, right?

In my understanding, the ViewModel pattern was designed to pass all the relevant data to View because 1) the view shouldn't perform any data retrieval or application logic and 2) it enables type-safety, compile-time checking, and editor intellisense…
randomguy
  • 12,042
  • 16
  • 71
  • 101
2
votes
2 answers

ASP.NET MVC: Passing instance variables to the View like in Ruby

Yes, I know that in ASP.NET MVC you have to use ViewModels. But I'm tired of writing countless amounts of ViewModel classes. Besides I'd like to just pass the Validation model to the view, instead of that I have to pass the whole ViewModel, so I get…
Alex
  • 34,581
  • 26
  • 91
  • 135
2
votes
5 answers

Why Html.DropDownListFor requires extra cast?

In my controller I create a list of SelectListItems and store this in the ViewData. When I read the ViewData in my View it gives me an error about incorrect types. If I manually cast the types it works but seems like this should happen…
dcompiled
  • 4,762
  • 6
  • 33
  • 36
2
votes
1 answer

ASP MVC Access ViewData Array?

I have some viewdata that is generated by going through my repository to the database to grab some scheduling info. When the information is stored in the Viewdata, I noticed that the viewdata is enumerated. How could I access the enumerated items…
Jacob Huggart
  • 663
  • 2
  • 11
  • 30
2
votes
4 answers

Why is my ViewData list null? MVC 4

I have two models, question and answer. I want to insert a list of answers thru ViewModel to a question but it seems in my post method my list is getting null. That might be a bad implementation as well, because I am returning a model of my question…
vLr
  • 75
  • 1
  • 11
2
votes
2 answers

How to Use ViewData and ViewBag with Umbraco Surface Controllers

I have just spent 2 hours trying to work out why when I put a string in to View.Bag/ViewData inside my Surface controller, when I try and get the string back in the view I get null. In the end I have solved the problem by putting the string in to a…
Ayo Adesina
  • 2,231
  • 3
  • 37
  • 71
2
votes
2 answers

How much data can ViewBag, ViewData, Tempdata hold

What is the maximum size that ViewBag, ViewData, Tempdata can hold?
Hani Abidi
  • 25
  • 1
  • 6
2
votes
1 answer

BC30451: 'ViewData' is not declared - error on server

My MVC 3 project is building successfully in my development machine with Visual Studio 2010 + MVC 3. Last night I deployed a routine update to the live server for my MVC website. It was working fine on dev, but on deployment the entire site fell…
MJStanford
  • 21
  • 3
2
votes
2 answers

Is there a difference between ModelState and ViewData.ModelState?

In some ASP.NET MVC code examples, I see references to ModelState.IsValid, and in other examples I see references to ViewData.ModelState.IsValid. In my initial research, I see: ModelState is a public property in Controller class. ViewData is a…
Michael R
  • 1,547
  • 1
  • 19
  • 27
2
votes
4 answers

Passing ViewData to Partial View

Controller IEnumerable _myList = helper.ConvertToListAvgPosGa(locDataSetGACampaigns.Tables[0]); ViewData["hourlydata"] = _myList; i want to use pass this ViewData to my partial to fill a table i am using renderpartial to…
rao
  • 223
  • 2
  • 7
  • 17
2
votes
1 answer

Adding to ViewData[] collection from AuthorizeAttribute Extension

I wrote an extension class to customize my AuthorizeAttribute for my action methods and I'd like to be able to inject messages into my view when a certain condition is met. I"m using the below code to load up a shared view when a user is not…
Kyle
  • 10,839
  • 17
  • 53
  • 63
2
votes
1 answer

Read retrieved json data using jquery in View mvc 3

I declared and serialized data on my View page @model IEnumerable @{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var employees = @serializer.Serialize(ViewData["Employees"]); …
Francis Padron
  • 307
  • 2
  • 7
  • 15
2
votes
3 answers

Why i can't call the Model and ViewData, and Html in the strong typed page?

I created a new strong typed View ,something like this: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
user196424
  • 41
  • 5
2
votes
2 answers

Create a base view model, but can't seem to hook into it in OnActionExecuting

I create a baseviewmodel that my other strongly typed view models inherit from. BaseController: protected override void OnActionExecuting(ActionExecutingContext filterContext) { var baseViewModel = ViewData.Model as BaseViewModel; …
loyalflow
  • 14,275
  • 27
  • 107
  • 168