asp.net-mvcperformancehtml.actionlinkmaster-pages

When using ASP.NET MVC, what is the best way to update multiple page sections with one HTML.Action() method?


I have a pretty big ASP.NET MVC site with 100 controllers and thousands of actions. Previously the header image that was defined on the Site.Master page was hardcoded and I want to make it dynamic.

To do so, I added this line to my Site.Master file:

<%= Html.Action("GetHeaderTitle", "Home")%>

which just returns some HTML for the header title such as:

<span style='font-size:15px;'>My Header Title</span>

The issue is that <title> also had this same hard coded value. I could obviously create another HTML.Action to have it show the dynamic valid in the title, but now I am going back to the server twice for essentially the same information (not the exact same HTML as I don't want the span information, but the same logic on the server to get the data).

Is there a way to have an Html.Action return multiple snippets of HTML that I can updates in different places on my master page?


Solution

  • I think you're looking at it wrong - if retrieving of the title is a long operation then just cache the results and write different actions anyway.

    // Controller
    public string GetTitle()
    {
        var title = (string)ControllerContext.HttpContext.Items["CachedTitle"];
        if (string.IsNullOrEmpty(title))
        {
            title = "some lengthy retrieval";
            ControllerContext.HttpContext.Items["CachedTitle"] = title;
        }
        return title;
    }
    
    public ActionResult GetTitleForTitle()
    {
        return Content(GetTitle());
    }
    
    public ActionResult GetHeaderTitle()
    {
        return Content("<span>"+ GetTitle() + "<span>");
    }
    

    Alternatively, you can cache it directly on the view, which is kind of evil (the simpler view the better):

     <%
       ViewBag.CachedTitle = Html.Action("GetHeaderTitle", "Home");
     %>
     ...
     <%= ViewBag.CachedTitle %>
     ...
     <%= ViewBag.CachedTitle %>