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
366
votes
17 answers

What's the difference between ViewData and ViewBag?

I saw the ViewBag in MVC 3. How's that different than ViewData in MVC 2?
user469652
  • 48,855
  • 59
  • 128
  • 165
188
votes
9 answers

Pass Additional ViewData to a Strongly-Typed Partial View

I have a strongly-typed Partial View that takes a ProductImage and when it is rendered I would also like to provide it with some additional ViewData which I create dynamically in the containing page. How can I pass both my strongly typed object and…
Nathan Taylor
  • 24,423
  • 19
  • 99
  • 156
106
votes
9 answers

How to set ViewBag properties for all Views without using a base class for Controllers?

In the past I've stuck common properties, such as the current user, onto ViewData/ViewBag in a global fashion by having all Controllers inherit from a common base controller. This allowed my to use IoC on the base controller and not just reach out…
Scott Weinstein
  • 18,890
  • 14
  • 78
  • 115
87
votes
10 answers

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

There are a couple of posts about this on Stack Overflow but none with an answer that seem to fix the problem in my current situation. I have a page with a table in it, each row has a number of text fields and a dropdown. All the dropdowns need to…
Jimbo
  • 22,379
  • 42
  • 117
  • 159
45
votes
6 answers

keep viewdata on RedirectToAction

[AcceptVerbs(HttpVerbs.Post)] public ActionResult CreateUser([Bind(Exclude = "Id")] User user) { ... db.SubmitChanges(); ViewData["info"] = "The account has been created."; return RedirectToAction("Index",…
Thomas Stock
  • 10,927
  • 14
  • 62
  • 79
35
votes
2 answers

ViewBag vs ViewData performance difference in MVC?

I know that ViewData and ViewBag both use the same backing data and that neither are as good as using strongly typed models in most cases. However when choosing between the two is the dynamic nature of ViewBag slower than using ViewData?
user169867
  • 5,732
  • 10
  • 39
  • 56
33
votes
4 answers

Argh! Why does System.Web.Mvc.HandleErrorInfo get passed to my views?

I'm experiencing a rather frustrating problem. My MVC site runs fine for the most part, but randomly throws an error (which shows a friendly error to the user). When I check the logs, this is what I get: System.InvalidOperationException: The model…
Chaddeus
  • 13,134
  • 29
  • 104
  • 162
28
votes
6 answers

Html.HiddenFor value property not getting set

I could have used @Html.HiddenFor(x=> ViewData["crn"]) but, I get, To somehow circumvent that issue(id=ViewData_crn_ and name=ViewData[crn]), I tried doing the following,…
Sekhar
  • 5,614
  • 9
  • 38
  • 44
20
votes
4 answers

ASP.NET MVC ViewData if statement

I use the following in my View to check if a query exists like domain.com/?query=moo if (!string.IsNullOrEmpty(Request.QueryString["query"])) { my code } But now need to change it so that it checks if the ViewData query exists instead of the query…
Cameron
  • 27,963
  • 100
  • 281
  • 483
14
votes
4 answers

How do you persist querystring values in asp.net mvc?

What is a good way to persist querystring values in asp.net mvc? If I have a url: /questions?page=2&sort=newest&items=50&showcomments=1&search=abcd On paging links I want to keep those querystring values in all the links so they persist when the…
dtc
  • 10,136
  • 16
  • 78
  • 104
14
votes
1 answer

ASP.NET MVC - Pass Json String to View using ViewData

I'm trying to pass Json to my View using ViewData Controller ViewData("JsonRegionList") = Json(RegionService.GetActiveRegions()) view $("input#UserRegion").autocomplete({ source:"<%: ViewData("JsonRegionList").ToString %>", …
Chase Florell
  • 46,378
  • 57
  • 186
  • 376
14
votes
1 answer

Storing data in HttpContext.Current.Items vs ViewData

When is it appropriate to store data in HttpContext.Current.Items[...] vs storing data in ViewData[...]? I'm trying to figure out the best practices for storing data in this collection and I'm not sure if it's safe to store user-specific data in…
Petrus Theron
  • 27,855
  • 36
  • 153
  • 287
14
votes
2 answers

How do I pass ViewData to a HandleError View?

In my Site.Master file, I have 3 simple ViewData parameters (the only 3 in my entire solution). These ViewData values are critical for every single page in my application. Since these values are used in my Site.Master, I created an abstract…
Luc
  • 1,830
  • 2
  • 23
  • 38
12
votes
4 answers

asp.net mvc. Passing a list via viewData

Hi does anyone know how to pass a list throught the "ViewData". This is what I'm trying but I think I'm missing a cast some where. List galleryList = new List(); galleryList.Add(new GalleryModel() { isApproved =…
RayLoveless
  • 19,880
  • 21
  • 76
  • 94
12
votes
4 answers

When is it right to use ViewData instead of ViewModels?

Assuming you wanted to develop your Controllers so that you use a ViewModel to contain data for the Views you render, should all data be contained within the ViewModel? What conditions would it be ok to bypass the ViewModel? The reason I ask is I'm…
DaveDev
  • 41,155
  • 72
  • 223
  • 385
1
2 3
21 22