10

How can I remove all white-spaces from ASP.NET MVC 3 output?


UPDATE: I know how can I use string.Replace method or Regular Expressions to remove white-spaces from a string; But I don't know, how can I use theme in ASP.NET MVC 3 for remove all white-spaces from output-string. For example, when the "OnResultExecuted" method invoked, and the result is ready to send to the end-user's browser, I want to obtain result - as a String, or a Stream object; not difference between them -, and do my job on it. Thanks to all. :)

amiry jd
  • 27,021
  • 30
  • 116
  • 215
  • 3
    If I understand Javad correctly, the question is about removing extra whitespace from the final HTML output for the entire page. Bring up msn.com and look at the source and it will become clear. I think IIS compression will resolve help, but there must be more to be gained by stripping the whitespace or msn.com wouldn't be doing it. In web forms we did this with a module. Not sure if all the hooks are still there in MVC. http://www.codeproject.com/Articles/38067/Compress-Response-And-HTML-WhiteSpace-Remover.aspx – Sam Mar 12 '11 at 03:36
  • I found the following stackoverflow question: http://stackoverflow.com/questions/2935657/asp-net-mvc-compress-stream-and-remove-whitespace – Valamas Jul 13 '11 at 22:35

4 Answers4

19

I found my answer and create a final solution like this:

First create a base-class to force views to inherit from that, like below, and override some methods:

  public abstract class KavandViewPage < TModel > : System.Web.Mvc.WebViewPage < TModel > {

      public override void Write(object value) {
          if (value != null) {
              var html = value.ToString();
              html = REGEX_TAGS.Replace(html, "> <");
              html = REGEX_ALL.Replace(html, " ");
              if (value is MvcHtmlString) value = new MvcHtmlString(html);
              else value = html;
      }
      base.Write(value);
  }

  public override void WriteLiteral(object value) {
      if (value != null) {
          var html = value.ToString();
          html = REGEX_TAGS.Replace(html, "> <");
          html = REGEX_ALL.Replace(html, " ");
          if (value is MvcHtmlString) value = new MvcHtmlString(html);
          else value = html;
      }
      base.WriteLiteral(value);
  }

  private static readonly Regex REGEX_TAGS = new Regex(@">\s+<", RegexOptions.Compiled);
  private static readonly Regex REGEX_ALL = new Regex(@"\s+|\t\s+|\n\s+|\r\s+", RegexOptions.Compiled);

  }

Then we should make some changes in web.config file that located in Views folder -see here for more details.

    <system.web.webPages.razor>
      <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <pages pageBaseType="Kavand.Web.Mvc.KavandViewPage"> <!-- pay attention to here -->
        <namespaces>
          <add namespace="System.Web.Mvc" />
          ....
        </namespaces>
      </pages>
    </system.web.webPages.razor>
Community
  • 1
  • 1
amiry jd
  • 27,021
  • 30
  • 116
  • 215
  • 1
    Excellent! Only issue I've seen is with this is on the bundling but I don't like the way MVC does that so I'm using this. Thanks +1 – Jamie Aug 13 '14 at 19:26
  • 1
    Because there are now both the HtmlString and MvcHtmlString types, I modified the `if (typeof` line to read `if (typeof(HtmlString).IsAssignableFrom(value.GetType()))`. This change lets your solution work flawlessly in my MVC5 project where those two types are used interchangeably (MvcHtmlString inherits from the newer HtmlString). – justisb Oct 21 '15 at 22:31
  • I replace if (typeof... with if (value is MvcHtmlString) value = new MvcHtmlString(html); else if (value is HtmlString) value = new HtmlString(html); else value = html; – Sel Mar 04 '16 at 07:46
  • does this handle `
     valid spaces we don't want to remove 
    `
    – Seabizkit Jul 28 '17 at 11:31
  • @Seabizkit no :( – amiry jd Jul 30 '17 at 12:37
  • @amiryjd, I can tell you your Regex implementation does not follow high-throughput multi-threaded best practices for Regular Expression objects in .NET. You need to have your regex as a static and have it access a [ThreadStatic] Regex underlying it. Then, on first access you need to initialize your Regex. Without this, there are multi-threading performance issues underlying the Regex object. – Jeff Fischer Apr 13 '22 at 18:00
  • 1
    @JeffFischer Thanks for the point. Ill update the answer. – amiry jd Apr 16 '22 at 07:17
2

one way you can, is that create a custom view page's inheritance; in that, override Write() methods (3 methods will be founded), and in these methods, cast objects to strings, remove white-spaces, and finally call the base.Write();

0

You could use the String.Replace method:

string input = "This is  text with   ";
string result = input.Replace(" ", "");

or use a Regex if you want to remove also tabs and new lines:

string input = "This is   text with   far  too   much \t  " + Environment.NewLine +
               "whitespace.";
string result = Regex.Replace(input, "\\s+", "");
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 5
    Thanks dear Darin Dimitrov, but I know this, I want to remove white-spaces from output-string to the browser, when the page rendered.For example when the "OnResultExecuted" method invoked and result is ready to send to the end-user. Thanks again for your help. – amiry jd Mar 04 '11 at 19:01
-5
 Str = Str.Replace(" ", "");

should do the trick.

Brandon Frohbieter
  • 17,563
  • 3
  • 40
  • 62
  • 2
    no dear; I know how to use String.Replace method, please read my question again; however I found my answer. – amiry jd Jul 25 '11 at 06:23
  • 2
    um, not sure why you commented on this many months later, but if you look at the time i posted my answer, it is quite a while before you actually updated the question with any useful information. – Brandon Frohbieter Jul 27 '11 at 22:05