ASP.NET MVC Master Page Data

a 夏天 提交于 2019-12-05 16:33:55

That works, although it's not the way I would do it for 2 reasons:

  1. I don't like sticking data into ViewState since you essentially cast it as object
  2. By requiring a base controller you're limiting the functionality to controllers that inherit from this basecontroller (which might not be an issue though)

I think this would be a perfect use of RenderAction (part of the MvcFutures project). This helper can be used to render an Action on another controller. So you might have a ProductController with a ListCategories action, you could just do something like:

<% Html.RenderAction<ProductController>(x => x.ListCategories()); %>

ListCategories would call

_service.GetCategories();

and might stick the info into its own Model. Then it would pass that model to the View would would be a Partial Page.

Thank you - RenderAction was perfect the job.

I got more information from here.

So for the benefit of others, here is an example of how I am outputting cart status:

Action:

    [ChildActionOnly]
    public ActionResult CartStatus()
    {
        return PartialView(_service.GetCartSummary());
    }

Partial View (bound to Models.Cart)

<div class="cartSummary">
<%if (Model.HasItems) { %>
    Cart Items: <%=Model.Items.Count() %> | Total: <%=Model.TotalItems %>
<%} else {%>
    Your cart is empty. Please buy stuff!
<%} %>

Helper method for Master Page:

    public static void RenderCartStatus(this ViewMasterPage pg) {
        pg.Html.RenderAction("CartStatus", "Catalog", null);
    }

And finally master page:

<%this.RenderCartStatus(); %>

Thank you for the advice.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!