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

ASP.NET MVC 2 - ViewData empty after POST

I don't really know where to look for an error... the situation: I have an ASPX view which contains a form and a few input's, and when I click the submit button everything is POST'ed to one of my ASP.NET MVC actions. When I set a breakpoint there,…
Alex
  • 75,813
  • 86
  • 255
  • 348
3
votes
1 answer

Can I access the ViewData from the HttpContext?

Im working with a project that sets variables such as the current user profile object in its authorize action filter, storing them in the ViewData for access by the following action method. The action method then calls functionality from the…
Jimbo
  • 22,379
  • 42
  • 117
  • 159
3
votes
4 answers

how to read data from json to View using jquery mvc

I have the following data in an array. [{"FirstName":"Nancy","LastName":"Davolio","Title":"Sales Representative"}, {"FirstName":"Andrew","LastName":"Fuller","Title":"Vice President, Sales"}] I want to present this data using jquery into a table…
Francis Padron
  • 307
  • 2
  • 7
  • 15
2
votes
1 answer

Fill ViewData on Every Action but not on renderaction

I have a viewData that is required to be available on each page. If I fill this ViewData using onActionExecuting. It gets filled for every action even for actionresult of partial pages. I want ViewData to be get filled only once for each Page Load.…
Tassadaque
  • 8,129
  • 13
  • 57
  • 89
2
votes
2 answers

How should we pass a data to a view in a big ASP.NET MVC web site

First of all, I have been a php programmer for a long time and I am a mvc programmer newly. I did a few minor web sites that each have one or two controller at most. But I've started a website that will be very major web site. There will be a lot of…
oruchreis
  • 866
  • 2
  • 12
  • 28
2
votes
1 answer

MVC3 Pass additional data from ctrl to view

If I were to pass additional data (other than the model) into my view, like say a list of files from a specific folder, whats the best way to do that? I was thinking something like making a method and return a list into ViewData: public…
Kasper Skov
  • 1,954
  • 10
  • 32
  • 53
2
votes
1 answer

How to display list of names present in viewdata in asp.net

I have a list of names in viewdata, but am not able to display it in view page <%= ViewData["names"].ToString() %> Thanks
Thomas Mathew
  • 1,151
  • 6
  • 15
  • 30
2
votes
2 answers

How to pass List of objects from view to controller action in asp.net mvc3

i have comprehensive search that returns several lists of objects. Each such list is made of objects containing additional lists. The search is very complex in terms of processor load. once i have the results, i display the original objects via…
Zaak
  • 482
  • 11
  • 25
2
votes
2 answers

Populating dropdownlist with selectlist in ViewData

I'm trying to populate an HTML. Dropdownlist with a selectlist which is populated with a string value (a location address) and text (a location description) fields from a database call. I am passing the selectlist as viewdata to my view. The…
2
votes
1 answer

Javascript error with Viewdata

I have a link that goes to a controller that renders a page that includes this javascript. $(document).ready(function () { var creditCards = '<%:(ViewData["CreditCards"])%>'; alert(creditCards); if (creditCards != null) { …
Collin O'Connor
  • 1,351
  • 4
  • 19
  • 31
2
votes
4 answers

Alternatives to ViewData?

I'm pretty new to MVC, ASP.net, and, well, server-side scripting in general. I was watching a tutorial video at www.asp.net/mvc where the person was explaining a template. He explained that the controller using viewdata to send information to the…
DarkLightA
  • 14,980
  • 18
  • 49
  • 57
2
votes
1 answer

How to read List<> passed to View via ViewData in ASP.Net MVC 2

I'm pretty new to ASP.Net MVC. I've created a model that fills a List<> with multiple custom objects called "Result". Then, in my controller, I get this List and put it into the ViewData. I am at a bit of a loss as to how to utilize this List in…
alchemical
  • 13,559
  • 23
  • 83
  • 110
2
votes
3 answers

Accessing a database object (and other important data) in the View

I know it's a bad practice to use database in the view. However, I'm also passing the User object and I wonder how I can make it easy to use. I love the way it works in Ruby On Rails. You just create an @instance_variable in before_filter and call…
Alex
  • 34,581
  • 26
  • 91
  • 135
2
votes
4 answers

Loop through Model property with Razor in MVC View

I have this Model with a lot of properties public class Task { public string Key { get; set; } public string Title { get; set; } public string Description { get; set; } .... } I need to create a table in the View to list all the…
Sergio
  • 250
  • 1
  • 4
  • 18
2
votes
4 answers

Casting ViewData in asp.net MVC

Here is my controller code : public ActionResult Index() { AccountModel user = new AccountModel(); user.Username = "Jay"; user.Password = "Jay"; ViewData["EmpData"] = user; return View(); } How…
iJade
  • 23,144
  • 56
  • 154
  • 243