Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

MVC Extension: MinifiedPartial

0.00/5 (No votes)
12 Jul 2012 1  
An extension for minimizing HTML output from a partial view

Introduction

I use partial views a lot in my razor views. And I do care about optimizing my HTML. So I created an extension to HTML-optimize my partial views and thought I'd share it with you.

Using the Code

Use it just as you use @Html.Partial().

@Html.MinifiedPartial("MyPartialView")

The Extension Method

// code
public static class MvcExtensions
{
    private static readonly Regex RegexBetweenTags = new Regex(@">(?! )\s+", RegexOptions.Compiled);
    private static readonly Regex RegexLineBreaks = 
    	new Regex(@"([\n\s])+?(?<= {2,})<", RegexOptions.Compiled);

    public static MvcHtmlString MinifiedPartial(this HtmlHelper htmlHelper, string partialViewName)
    {
        var partialViewContent = htmlHelper.Partial(partialViewName).ToHtmlString();

        partialViewContent = RegexBetweenTags.Replace(partialViewContent, ">");
        partialViewContent = RegexLineBreaks.Replace(partialViewContent, "<");

        return new MvcHtmlString(partialViewContent);
    }

    public static MvcHtmlString MinifiedPartial
    	(this HtmlHelper htmlHelper, string partialViewName, object model)
    {
        var partialViewContent = htmlHelper.Partial(partialViewName, model).ToHtmlString();

        partialViewContent = RegexBetweenTags.Replace(partialViewContent, ">");
        partialViewContent = RegexLineBreaks.Replace(partialViewContent, "<");

        return new MvcHtmlString(partialViewContent);
    }
} 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here