Remove Unnecessary Space And Line Break From MVC ASP.NET
When the size of the HTML page that is rendered to the end user browser is really big, it has few disadvantages:
- The page loads slow
- Unnecessary space in the html don't serve any purpose to the page, then why have anything unncessary.
- Compression of HTML at the IIS response level.
- Compression of HTML using GZip compression at the application level.
-
Create a codebehind file for the master page by following the instructions below:
- Right click on the folder containing the master file. Select Add New Item option.
- Select class item template and name the class as the name of the master file with .master.cs as extension.
-
Now Inherit the Website.Master.cs in the Website.Master
This can be done by changing the Master directive:
Before:
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
After:
<%@ Master Language="C#" Inherits="AltafKhatri.Views.Shared.WebSite" %>where:
AltafKhatri.Views.Shared : is the namespace of the master code behind file and WebSite : is the name of the master codebehind file. -
In the codebehind of the master file use the following references:
Paste the code below in the master page code behind:- using System.Web.UI;
- using System.Text.RegularExpressions;
namespace AltafKhatri.Views.Shared
{
public partial class WebSite : System.Web.Mvc.ViewMasterPage
{
private static readonly Regex REGEX_BETWEEN_TAGS = new Regex(@">\s+<", RegexOptions.Compiled);
private static readonly Regex REGEX_LINE_BREAKS = new Regex(@"\n\s+", RegexOptions.Compiled);
protected override void Render(HtmlTextWriter writer)
{
using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
{
base.Render(htmlwriter);
string html = htmlwriter.InnerWriter.ToString();
html = REGEX_BETWEEN_TAGS.Replace(html, "> <");
html = REGEX_LINE_BREAKS.Replace(html, string.Empty);
writer.Write(html.Trim());
}
}
}
}
I know MVC framework discourages having code behind but in this case I have made it the only exception. It has not hurt my MVC architecture and the performance of the website.
I will be glad to hear the comments and suggestions about different ways to handle this in MVC.
Reference(s) for this article: http://madskristensen.net/post/Remove-whitespace-from-your-pages.aspx
