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

There is no ViewData item with the key 'Blah' of type 'IEnumerable'

This error message is driving me nuts. I'm getting it when using Html.ListBox and Html.DropDownList HtmlHelpers with ASP.NET MVC v1.0. Populating the lists works OK - I can view them, etc - but when I go to create a new record in the Model using the…
Bernard
  • 652
  • 3
  • 7
  • 16
4
votes
2 answers

Maintaining ViewBag values while posting data

I have a logical question that needs to be answered!! Here is a scenario.. -In controller ViewBag.Name = "aaaa"; -In View @ViewBag.Name "In my controller, i have set value for ViewBag and retrieved value from ViewBag in VIew. Now in View, i have…
mmushtaq
  • 3,430
  • 7
  • 30
  • 47
4
votes
5 answers

ASP.NET MVC ViewData and view model best practices

The initial situation is that I map my domain model into a presentation model. I have to display an update/create formular with textboxes and a dropdownlist. Should the viewmodel contain a list for the dropdownlist or should I pass the data for the…
Rookian
  • 19,841
  • 28
  • 110
  • 180
4
votes
4 answers

Using ViewData to pass data from Controller to View

I'm trying to pass data from a controller to view, and display these data. But after many tries I can't. Controller code : public ActionResult ValidSearch(ProductSearchParam gp) { if (gp.IsCandidate) { ViewBag.abc="bob"; …
Antoine Ravier
  • 63
  • 1
  • 1
  • 9
4
votes
1 answer

Getting User Information using SimpleMembership

Still trying to get to grips to the new SimpleMembership with MVC4. I changed the model to include Forename and Surname which works fine. I want to change the information displayed when logged in so instead of using User.Identity.Name in the View I…
3
votes
2 answers

Need simple example of how to populate javascript array from Viewdata list

There may be a simpler way of doing this and I am all ears if there is. My situation is I have a dropdownlist on a form which I successfully populate with text and values. I also need to have additional related string values from the same table row…
MikeD
  • 741
  • 5
  • 20
  • 38
3
votes
5 answers

View data from view to controller

Is there an easy way to pass an object from my view to controller? I tried ViewData["newPerson"] but that didn't work. Session["newPerson"] works but are there other ways that are more recommended?
Rod
  • 14,529
  • 31
  • 118
  • 230
3
votes
2 answers

How do I get ViewData inside a form to display correctly?

<%:ViewData["galleryId"]%> <% using (Html.BeginForm( "FinishEdit" , "GalleryManager" , FormMethod.Post , new { enctype = "multipart/form-data" } ) ) {%> …
Collin O'Connor
  • 1,351
  • 4
  • 19
  • 31
3
votes
5 answers

Should ViewData never be used?

I have tried to check the best practices for using asp.net mvc and quite a few say that we should never use ViewData. I have read this post and it seems like it from that. One reason that I can think of using ViewData is if you are looking to pass…
Vishal
  • 12,133
  • 17
  • 82
  • 128
3
votes
2 answers

ASP.NET MVC strongly typed views or not?

What is the best practice - to use only strongly typed views without any parameters, that passes through the ViewData dictionary, or it's a not bad idea to use something like this in a view: <%: (string)ViewData["helloMessage"]%> Thanks.
Kai
  • 2,023
  • 7
  • 28
  • 49
3
votes
2 answers

Passing object to partial view using ViewData

I'm going to build a helper for my application which uses many wizards. For my views, there is simple call: @using (var wiz = MyHelper.EditWizard(Translate(Keys.User.ChangePasswordTitle))) { // RenderPartial(...) } whereas MyHelper is a…
KingKerosin
  • 3,639
  • 4
  • 38
  • 77
3
votes
3 answers

HTML markup rendering issue in ViewData? Also, MultiView functionality in MVC?

i'm trying to populate a ViewData instance with html markup like shown below. When the page renders, the html tags get rendered as text and not html markup. Anyone know why? Controller code: if (user.ActivationStatus == false) { ... …
shahidaltaf
  • 585
  • 1
  • 5
  • 17
3
votes
1 answer

Should I always use a view model or is it ok to use ViewData?

when do you think is it better to use ViewData over a view model? I have the same exact partial view in a couple of main views. I'd like to control how a partial view is rendered but I'd also prefer the partial view to accept only a view model which…
Celdor
  • 2,437
  • 2
  • 23
  • 44
3
votes
1 answer

Where ViewData and ViewBag reside?

Note: This is not duplicate of this question as it does not answer the question completely. My question is where exactly it get stored when you assign a value to ViewData or ViewBag like TempData resides in Session. Both resides in Session too? If…
Priyank Sheth
  • 2,352
  • 19
  • 32
3
votes
1 answer

Partial parameters using both ViewData Dictionary and the ViewBag deletes ViewBag data

I need to pass some information to a partial cshtml view. I use a ViewDataDictionary and the ViewBag for that. public ActionResult TaskPage(int ID = 0) { ViewBag.breadcrumbs = new string[] { "List", "Tasks" }; ViewBag.title =…
nest
  • 1,385
  • 1
  • 15
  • 34