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

ASP.NET MVC Passing Raw HTML from Controller to View

I have been scratching my head about this for a few days, and I am not sure if it is an issue with my environment or the code itself basing this on being to ASP.NET MVC (although I have 5 years experience in C#). I am using a recent clean install of…
Dave
  • 1,823
  • 2
  • 16
  • 26
6
votes
6 answers

passing viewdata to asp.net mvc masterpages

I'm trying to pass ViewData to my asp.net mvc masterpage for an mvc usercontrol that I keep on a masterpage. For example, I created a dropdownlist of names as an mvc usercontrol and I put that in my masterpage. The problem I am running into is…
codette
  • 12,343
  • 9
  • 37
  • 38
6
votes
4 answers

Where should I put my asp.net-mvc strongly typed viewdata?

I've been nesting my viewdata classes inside my controllers and, as their numbers grow, I'm starting to ask myself if this is a good idea. Then again, something about polluting the /Views and /Controllers directories with these things seems off. Is…
Dane O'Connor
  • 75,180
  • 37
  • 119
  • 173
6
votes
1 answer

ASP.NET Core ViewData access in javascript

I am sending a filepath ( string) from controller to html page through ViewData and I want to access that string in my javascript, consume it, run some algo in javascript and then use results to consume them and make some graphs on the same html…
Muhammad Touseef
  • 4,357
  • 4
  • 31
  • 75
6
votes
1 answer

What is the difference between Session and ViewData in Asp.net-MVC?

When should I use one versus the other? I want to cache a certain object on startup and reuse around the application. Which sounds like the better solution (ViewData or Session)?
leora
  • 188,729
  • 360
  • 878
  • 1,366
6
votes
6 answers

LINQ Anonymous Types + MVC Views

I've seen many questions about this, but i've never really got the answer that I need. I'm converting a fairly large web application from Web Forms to MVC and after a while I encountred a problem with passing data to the view. In the Action I…
impClaw
  • 63
  • 1
  • 6
6
votes
1 answer

How to load HTML Table in MVC using ViewData?

I have the following table in my View:
1 2 3 …
Bryuk
  • 3,295
  • 10
  • 45
  • 74
5
votes
1 answer

The name 'ViewData' does not exist in the current context

I am working over my first application over MVC3 and still kind of a newbie in it: I’m trying to success my ViewData[] over a master page because its contains a message that would be used over every page, but when I’m trying to access that it…
Maven
  • 14,587
  • 42
  • 113
  • 174
5
votes
2 answers

mvc no codebehind strongly typed viewdata headers not working

I add that to my header <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> and am able to access ViewData and all its internals as well as all the mvc objects like url and html. As soon as I add…
Ayo
  • 1,198
  • 2
  • 16
  • 36
5
votes
1 answer

Why would =ViewData[""] show a string but evaluating it for the same string fail?

//CHECK IF WE SHOULD SHOW THE PASSWORD HINT OR NOT Setting passwordhints; using (var db = new dbDataContext()) { passwordhints = (from c in db.Settings where c.Name == "ShowPasswordHints" && c.ID == _ID select…
MetaGuru
  • 42,847
  • 67
  • 188
  • 294
5
votes
2 answers

ASP.NET MVC 3 RC - Razor "View" Property

Just mucking around with Razor in the ASP.NET MVC 3 RC released today. Now, we have a concept of a "Layout Page", which i presume is the replacement of the "View Master" in the ASPX view engine. But i do not understand the "View" property of the…
RPM1984
  • 72,246
  • 58
  • 225
  • 350
5
votes
1 answer

There is no ViewData item of type 'IEnumerable' that has the key 'Carrera'

I'm having trouble when handling the Post request for my controller: [HttpGet] public ActionResult Crear() { CarreraRepository carreraRepository = new CarreraRepository(); var carreras = carreraRepository.FindAll().OrderBy(x => x.Nombre); …
delete
5
votes
4 answers

Can't access ViewData in a partial view in ASP.NET MVC3

I have a controller calling a view. In the view there is a partial view, inserted like this: @{ Html.RenderPartial("PartialViewName", this.Model);} This works fine. But in the controller I wish to put something in the ViewData or ViewBag that I…
Victor
  • 235
  • 1
  • 5
  • 14
4
votes
2 answers

ASP.NET MVC: How to handle cross-action TempData and ViewData

I'm trying to find a good way to handle the following scenario (I'm still kinda new to this): A user can register through my site using an RPX/OpenId provider. Step 1: The user authenticates through a provider. The provider returns a temporary token…
Denny Ferrassoli
  • 1,763
  • 3
  • 21
  • 40
4
votes
5 answers

ASP.net mvc Common data for footer

So, I have a footer which will appear on every page of my web application I need it to render dynamic data so.... this means that every controller action needs to return viewData which contains this data.. as well as the action specific data How…
iasksillyquestions
  • 5,558
  • 12
  • 53
  • 75
1 2
3
21 22