Click here to Skip to main content
12,298,406 members (44,874 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

6.6K views
Posted

MVC Extension: MinifiedPartial

, 12 Jul 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

StianSandberg
Software Developer (Senior) Aurum AS
Norway Norway
Microsoft Certified Solutions Developer (MCSD)

Personal website:
stian.net

My projects:
CRM1.no - A free to use norwegian crm software
Fakturax - A free to use norwegian invoice software
Timeføring.no - A free to use norwegian timereg software
MittUtlegg - A free to use norwegian software for receipts
SupportWeb - A free to use norwegian software customersupport

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160525.2 | Last Updated 12 Jul 2012
Article Copyright 2012 by StianSandberg
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid