ASP.Net MVC menu with cache

I am trying to create a menu for my site. It must meet the following requirements

  • it must be managed by the database, pulling data from the database to create a menu structure.
  • data retrieved from the database must be cached - I do not want to hit the database for every page request

At the moment I have a simplified example, but I do not know how to integrate caching. I think that I may have to rework this whole way. Here it is:

I have a ProductMenuAttribute that retrieves data from a database and stores it in ViewData:

public class ProductMenuAttribute: FilterAttribute, IActionFilter
{
    #region IActionFilter Members

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext != null)
        {
            var context = filterContext.Result as ViewResult;
            if (context != null)
            {
                ProductsRepository repository = new ProductsRepository(Properties.Settings.Default.SqlConnectionString);

                context.ViewData.Add("ProductsList", repository.GetAllProductRanges());
            }
        }
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {

    }

    #endregion
}

Site.master ViewDataโ€‹โ€‹strong > . , CSS. :

            <li>
                <%= Html.ActionLink("Products", "Index", "Products")%>

                <%  IQueryable<ProductRange> productRanges = ViewData["ProductsList"] as IQueryable<ProductRange>; %>

                    <% if (productRanges != null)
                       { %>

                    <ul>
                        <% foreach (ProductRange range in productRanges) 
                           { %>   
                            <li><%= Html.ActionLink(range.Name, "RangeDetails", "Products", new { id = range.ID }, null)%></li>
                        <% } %>
                    </ul>

                    <% } %>
            </li>

[ProductMenu] :

[ProductMenu]
public class HomeController : BaseController
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

, - , OnActionExecuted ProductMenuAttribute, ViewData, Site.Master, , .

- ? , , , , , .

+5
3

, , Html.RenderAction() MVC Futures.

, , , HTML, . .

, , , .

: - Html.RenderAction Html.Action. , , .

, Html.RenderAction() ViewUserControl OutputCaching :

<@ OutputCache Duration="100" VaryByParam="None" %>

Html.RenderPartial(), , !

+6

: . : http cache.

+1

I did this using the corporate library caching unit. You check the cached data, if there is no cached data, you create an html string from the data in your database and put it in the cache, so later, when searching for cached data, you can simply output a string string: D

Just mention that the code for this was in a static class. Ill post example, but I rewrite this application in MVC2 from scratch, so I don't have the code manually.

0
source

All Articles