Search code examples
asp.net-mvchtml-helper

Is this HtmlHelper extension overkill?


I've implemented a custom html helper extension method to render a partial view into my razor page and I'm concerned that the method I've used is "too heavy"...

I want to use a common spinner across my web project. The spinner I'm using requires a number of elements:

<div class="panel-spinner-container">
    <div class="sk-spinner sk-spinner-cube-grid">
        <div class="sk-cube"></div>
        <div class="sk-cube"></div>
        <div class="sk-cube"></div>
        <div class="sk-cube"></div>
        <div class="sk-cube"></div>
        <div class="sk-cube"></div>
        <div class="sk-cube"></div>
        <div class="sk-cube"></div>
        <div class="sk-cube"></div>
    </div>
    <div class="panel-spinner-msg"><p>loading...</p></div>
</div>

Rather than including this in razor code every time I want a spinner, I figured I'd toss it into an html helper method, so I could do this:

<div>
    @Html.PanelSpinner()
</div>

I created a partial view for this which just contains the divs from above, and an html helper extension method:

public static MvcHtmlString PanelSpinner(this HtmlHelper html) {

    var controllerContext = html.ViewContext.Controller.ControllerContext;
    var viewData = html.ViewData;
    var tempData = html.ViewContext.TempData;

    using (var stringWriter = new System.IO.StringWriter()) {

        var viewResult = ViewEngines.Engines.FindPartialView(controllerContext, "PanelSpinner");
        var viewContext = new ViewContext(controllerContext, viewResult.View, viewData, tempData, stringWriter);

        viewResult.View.Render(viewContext, stringWriter);
        var stringResult = stringWriter.GetStringBuilder().ToString();

        return new MvcHtmlString(stringResult);
    }
}

This seems like an awful lot of processing required to render a spinner. What is the performance overhead on this type of method? Is it normal to use a helper for this type of scenario, or am I overkilling this? Is there a better (more performant) way to do this?

I very much like the ease of use but am concerned about performance (e.g., I could just use @Html.RenderPartial(...), but then I have to remember the name of the spinner partial, etc. The helper method wrapper is so much easier to use)


Solution

  • To render a partial view using an extension method, you can make use of the built in Partial() method of HtmlHelper. It can simply be

    public static MvcHtmlString PanelSpinner(this HtmlHelper html)
    {
        return html.Partial("PanelSpinner");
    }
    

    Note: You need to include using System.Web.Mvc.Html;