views:

66

answers:

4

Hi all,

So I've got a partial in my MVC project that creates a JSON array. I want to move this chuck of code from the top of the html page body to the bottom with the rest of the JS for speed reasons. That is to say I want to store the JSON created as a string in C# and access it on the Site.Master.

What's the best option here?

Thanks, Denis

+2  A: 

Hi,

When I need to access information in my MasterPage I create a BaseController and set the information in my ViewData :

public abstract class BaseController : Controller
{
    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);

        ViewData["JSonObject"] = "json string";
    }
}

Just have to inherit all controller from BaseController and it will work.

All views including MasterPage can access ViewData["JSonObject"] now!

Guillaume Roy
I've tried this and set the ViewData = test in the base and test2 in the partial. if I print it out in the partial it's test2. But if I print it out before or after that partial its value is test. ViewData doesn't seem to be maintained up, only down?
Denis Hoctor
The MasterPage must be generated before the partial views... you need to display test2 in the MasterPage??
Guillaume Roy
Yeah I need the data (JSON) that I'm creating on the partial but I don't want to write a script block in the middle of the page so need the Master Page to access it once it's been set on the partial.
Denis Hoctor
I'm not sure to understand why you need a string in your masterpage that have been set in a Partial. A Partial View should be used only to display information from an object or a view model... Did you solve your problem ??
Guillaume Roy
A: 

Just call RenderPartial in the MasterPage

Malcolm Frexner
A: 

Use ViewData to pass information around between the views.

In your partial:

ViewData["JsonString"] = ".....";

In the master page:

<%= ViewData[ "JsonString" ] %>
Jon Benedicto
This is what I tired to start will but its null when accessed on the master page.
Denis Hoctor
Then you must have accessed it before setting it.
Jon Benedicto
Sorry you mean I must have access the ViewData I assigned before I assigned it? I can see how I could have.
Denis Hoctor
A: 

Seems that ViewData is Top down only. So if you assign a value in the partials parent or a controller that'll work but not the other way round. I managed to get it working using Context.Item

Context.Items["JSONFeatures"] = "test"; on Partial Context.Items["JSONFeatures"].ToString(); on MasterPage

Hope this helps someone. I'm not sure if this is best practices but it works it I know better!

Denis Hoctor