Nested partial output caching in ASP.NET MVC 3

I use the Razor viewer in ASP.Net MVC 3 RC 2. This is part of my city.cshtml

(for simplification in simple simplified code)

 <!-- in city.cshtml --> <div class="list"> @foreach(var product in SQL.GetProducts(Model.City) ) { <div class="product"> <div>@product.Name</div> <div class="category"> @foreach(var category in SQL.GetCategories(product.ID) ) { <a href="@category.Url">@category.Name</a> » } </div> </div> } </div> 

I want to cache this part of my output using the OutputCache attribute, so I created a ProductList action with the OutputCache attribute enabled

 <!-- in city.cshtml --> <div class="list"> @Html.Action("ProductList", new { City = Model.City }) </div> 

and I created a view in ProductList.cshtml as shown below

 <!-- in ProductList.cshtml --> @foreach(var product in Model.Products ) { <div class="product"> <div>@product.Name</div> <div class="category"> @foreach(var category in SQL.GetCategories(product.ID) ) { <a href="@category.Url">@category.Name</a> » } </div> </div> } 

but I still need to cache category output for each product. so I created a CategoryPath action with the OutputCache attribute enabled

 <!-- in ProductList.cshtml --> @foreach(var product in Model.Products ){ <div class="product"> <div>@product.Name</div> <div class="category"> @Html.Action("CategoryPath", new { ProductID = product.ID }) </div> </div> } 

But, apparently, this is not allowed. I got this error:

OutputCacheAttribute does not allow child actions that are children of an already cached child action.

I believe that they have a good reason why they should ban it. I really want this nested output caching.

Any idea of ​​a workaround?

+4
source share
4 answers

In your SQL.GetCategories method, you can get all categories and cache it if it is not already in the cache. And filter the categories by productID using LINQ TO OBJECTS. This way you do not press db every time you need to find product categories.

Now you only use OutputCache in the ProductList, and you have a pretty decent execution (partial) view.

+1
source

Use Kids Cache For CategoryPath Action. There is also an example of ChildActionOnly in action .

+2
source

We had a similar problem, and it turned out that in fact we did not need nested partial output caching at all. Once we cached the parent, the child was not called again until the parent cache expired.

So my advice might be: Cache is the parent, and the child will already be processed.

+2
source

I don’t know much about MVC, but “nested caching” made me wonder why using alterbyparam will not work here ...

0
source

Source: https://habr.com/ru/post/1333507/


All Articles