Adam Rackis
Adam Rackis

Reputation: 83356

Pass ViewData to MVC user control

This is MVC 2

This is part of my user control

Foo = <%= ViewData["Foo"] %>

<ul id="menu" class="topTabMenu">
    <% foreach (X.Site s in X.AllSites) { %>
    ...

And this is how I'm calling it:

<% Html.RenderPartial("MenuTabsPartial", Model, new ViewDataDictionary(new { Foo = "Bar" })); %>

What do I have to do to get ViewData["Foo"] to display "Bar"? Is there some better way to pass some simple data to this partial?

Passing it in the Model will not work since I'm already using Model for something else.

EDIT

Manually assigning this value to TempData does work. Should I just use TempData instead? Can ViewData only be set from the Controller?

Upvotes: 1

Views: 825

Answers (2)

Kurt S
Kurt S

Reputation: 21357

I'm not sure that you can create a ViewDataDictionary with an anonymous object. Try overload taking another ViewDataDictionary. This should get your ViewData["foo"] to display "Bar".

Html.RenderPartial("MenuTabsPartial", Model, new ViewDataDictionary(new ViewDataDictionary { { "Foo", "bar" } }));

I've done this once or twice, but I would say you really should consider passing it in the Model. If your model isn't already a view model, then I would recommend making one with two properties: one that represents whatever "Model" currently is, and another one for "Foo". The Controller would set this up and pass it to the view.

class MyViewModel
{
    public TypeOfMainModel MainModel {get; set;} //put your current model here
    public string Foo {get; set;}
}

Have your view use this as the view model. Then when you render your partial you can just pass the whole model, or perhaps just give it Foo (if your partial view only needed a string):

Html.RenderPartial("MenuTabsPartial", Model.Foo);

The choice is yours, but creating a view model container that holds everything necessary for the View and any Partial View is my preferred approach.

Upvotes: 1

hawkke
hawkke

Reputation: 4262

According to Microsoft's documentation on ViewData, it:

Gets or sets a dictionary that contains data to pass between the controller and the view.

So, from that definition alone, I would say you are right in saying ViewData can only be set from the controller. If TempData works for you, I would use that. You might also try ViewBag if you aren't afraid of dynamics.

Edit: Ignore my comment about ViewBag, I didn't see your question was tagged with MVC2.

Upvotes: 1

Related Questions