Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net MVC RC1 RenderPartial ViewDataDictionary

Tags:

I'm trying to pass a ViewData object from a master page to a view user control using the ViewDataDictionary.

The problem is the ViewDataDictionary is not returning any values in the view user control whichever way I try it.

The sample code below is using an anonymous object just for demonstration although neither this method or passing a ViewData object works.

Following is the RenderPartial helper method I'm trying to use:

<% Html.RenderPartial("/Views/Project/Projects.ascx", ViewData.Eval("Projects"), new ViewDataDictionary(new { Test = "Mark" })); %> 

and in my view user control i do the following:

<%= Html.Encode(ViewData["Test"]) %> 

Why does this not return anything?

Thanks for your help.

EDIT:

I'm able to pass and access the strongly typed model without any problems. it's the ViewDataDictionary which I'm trying to use to pass say just a single value outside of the model...

like image 767
Mark79 Avatar asked Jan 30 '09 12:01

Mark79


People also ask

What is ViewDataDictionary in MVC?

In MVC, when we want to transfer the data from the controller to view, we use ViewData. It is a dictionary type that stores the data internally. ViewData contains key-value pairs which means each key must be a string in a dictionary. The only limitation of ViewData is, it can transfer data from controller to view.

How do I pass ViewData in partial view?

You're almost there, just call it like this: Html. RenderPartial( "ProductImageForm", image, new ViewDataDictionary { { "index", index } } ); Note that this will override the default ViewData that all your other Views have by default.

What is ViewBag and ViewData?

ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. ViewData requires typecasting for complex data type and check for null values to avoid error.

How do you use partial views?

To create a partial view, right-click on view -> shared folder and select Add -> View option. In this way we can add a partial view. It is not mandatory to create a partial view in a shared folder but a partial view is mostly used as a reusable component, it is a good practice to put it in the "shared" folder.


1 Answers

This is the neatest way I've seen to do this:

<% Html.RenderPartial("/Views/Project/Projects.ascx", Model, new ViewDataDictionary{{"key","value"}});%> 

It may be a little hackish, but it let's you send the model through AND some extra data.

like image 58
Alan Avatar answered Sep 21 '22 05:09

Alan