[ACCEPTED]-How can I remove white-spaces from ASP.NET MVC# output?-asp.net-mvc-3

Accepted answer
Score: 19

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

First create a base-class to force 4 views to inherit from that, like below, and 3 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 2 some changes in web.config file that located in Views folder 1 -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>
Score: 2

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

Score: 0

You could use the String.Replace method:

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

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

string input = "This is   text with   far  too   much \t  " + Environment.NewLine +
               "whitespace.";
string result = Regex.Replace(input, "\\s+", "");

More Related questions