Search code examples
asp.net-mvcasp.net-mvc-partialviewasp.net-mvc-viewmodel

Access partial view's model in parent view


I'm trying to access view model of a partial view in it's parent view (Home page) but, unable to do so!

My scenerio: I have a partial view with it's own controller and view model. there are 3 lists being populated from DB in partial view's model: Countries, cities, and categories.

I want to show categories on both partial view and it's parent with different pattern.

Note: As the partial view is being used on other pages (views) also so, I can't put Categories in Home view model instead of partial view model! And putting Categories list in both view models will cause double DB call for same data!

Can anyone please help in this regards. Thanks


Solution

  • You can't access partial view's model in parent view. But you can share data between them with HttpContext.Items.

    @{
        this.ViewContext.HttpContext.Items["Stuff"] = "some-data";
    }
    

    this data is valid for a single HTTP Request.

    More info:

    https://msdn.microsoft.com/en-us/library/system.web.httpcontext.items(v=vs.110).aspx

    When can we use HttpContext.Current.Items to stores data in ASP.NET?

    Edit: link corrected.