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
3 answers

Return multiple views to one ActionResult with ASP.NET MVC

What I want to achieve essentially is: Items assigned to me Item 1 assigned to me Item 2 assigned to me Item 3 assigned to me All open items Item 1 open to everyone Item 2 open to everyone Item 3 open to everyone Item 4 open to everyone Though…
LiamGu
  • 5,317
  • 12
  • 49
  • 68
2
votes
1 answer

Is it good practice to pass TempData and/or ViewData to services?

In trying to reduce the size of my MVC controllers, I am refactoring a lot of logic out into services (though this same issue would apply if it was being factored into models). I'm often finding that I was directly setting ViewData and/or TempData…
Jez
  • 27,951
  • 32
  • 136
  • 233
2
votes
2 answers

Using MVC3 ViewData inside Style attribute of div

I´m working on a MVC3 project. I already have a decimal value into a ViewData["nReceived"] calculated in the controller. After that the controller calls to Index view. I'm able to display it on Index view outside of a element
ɐsɹǝʌ ǝɔıʌ
  • 4,440
  • 3
  • 35
  • 56
2
votes
2 answers

Maintaining ViewData between RenderAction calls

I'm rendering a common Log-In form using Html.RenderAction, on every page of my site. If the user enters their details into the text-box and clicks 'Submit', it does a POST to a controller that handles the log in. If they make a mistake, such as…
Jonathan
  • 32,202
  • 38
  • 137
  • 208
2
votes
2 answers

MVC 3 Razor - Access ViewData in Ajax Request (Jquery, JavaScript)

I am writing some code where the user can check if a username already exists in the database before submitting the form. This works by on onkeyup event handler which takes the value from the textbox and passing it to an ajax request which calls my…
nick gowdy
  • 6,191
  • 25
  • 88
  • 157
2
votes
2 answers

Storing Additional Information About a Logged In ASP.NET MVC User

I need to store an ID against a user that will be used in EVERY action that is carried out on my web application. I had hoped to use a customized authorization ActionFilterAttribute (on an entire controller) to populate the ViewData with this…
Jimbo
  • 22,379
  • 42
  • 117
  • 159
2
votes
2 answers

Grails Controller data passed to view is null when accessed on view?

I have an application that has some controllers, views and layouts. I am basically trying to pass some data from the Controller to the view. The view in question uses a layout called main.gsp in the layouts folder. So I used the code below in order…
user723858
  • 1,017
  • 3
  • 23
  • 45
2
votes
1 answer

Trouble using viewdata of the Spark view engine to call a javascript function with parameters containing quotes

I'm developing a website using the Spark view engine. One of the spark views has viewdata defined that is used in javascript defined in that same spark view and looks (in short) like this:
1
vote
1 answer

Is the data inside the ViewData dictionary correlating to the Model Serialized?

In ASP.NET MVC3, when a view model is passed into a view using return View(myViewModel); it adds a definition to the ViewData dictionary, ViewData.Model, which holds myViewModel. In the view @model myViewModel will allow access of the view model…
Travis J
  • 81,153
  • 41
  • 202
  • 273
1
vote
1 answer

Pass UserId to the Model

So I have a simple web app where I can create a user (UserModel) and it returns that user ID. The user then has the ability to enter multiple instances or records of a specific item type, in this case a geographic location (LocationModel). The…
jamesamuir
  • 1,397
  • 3
  • 19
  • 41
1
vote
3 answers

Strongly typed master pages polymorphism - nested masterpages ignore inherit attribute

I'm currently creating a CMS system and found that the following doesn't work. I do have a work around that isn't exactly ideal and feels dirty. I'm cool with it for now and not really that interested in a different approach (but don't let that stop…
Charlino
  • 15,802
  • 3
  • 58
  • 74
1
vote
2 answers

In asp.net mvc, where do I put my strongly typed viewdata reference in my viewpage?

My viewpage doesn't have a codebehind, so how do I tell it to use a strongly typed viewdata?
mrblah
  • 99,669
  • 140
  • 310
  • 420
1
vote
1 answer

Javascript compare ViewData list values with DropDownlist Selected Item

I've searched around for the answer to this question but nothing that completely satisfies what I'm looking for. I have a dropdown list of items. When the user selects an item, I want to compare the selected value, with the items in 2 different…
jbizzle
  • 1,495
  • 2
  • 11
  • 11
1
vote
0 answers

ViewData and javascript - class name not being read

For some reason I'm having trouble assigning viewdata to some javascript. I have the following code: @{ string item = ".playerItem_" + ViewData["itemType"]; }