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

后端 未结 4 1951
自闭症患者
自闭症患者 2021-01-31 23:00

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 w

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-31 23:48

    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.

        
          
           
            
              
              ....
            
          
        
    

提交回复
热议问题