简体   繁体   English

MVC HTML自定义助手剪切空间

[英]MVC Html custom Helper cut spaces

I wrote helper 我写了助手

  public static class TestHelper
  {
    public static string Test(this HtmlHelper helper)
    {
        var writer = new HtmlTextWriter(new StringWriter(), string.Empty);
        //writer.InnerWriter.NewLine = string.Empty;
        //writer.NewLine = string.Empty;
        writer.RenderBeginTag(HtmlTextWriterTag.Ul);  //<ul>
        for (int i = 0; i < 5; i++ )
        {
          RenderRow(helper, writer, i);
        }
        writer.RenderEndTag();                        //</ul>
        return writer.InnerWriter.ToString();
    }

    private static void RenderRow(HtmlHelper helper, HtmlTextWriter writer, int i)
    {
      writer.RenderBeginTag(HtmlTextWriterTag.Li);
      writer.Write(i);
      writer.RenderEndTag();
    }
  }

and use it the same way: 并以相同的方式使用它:

@Html.Test()

but in result I see html tags in browser. 但结果是我在浏览器中看到html标签。 The problem is a space before the first tag: 问题是第一个标签之前有一个空格:

<ul> <li>0</li><li>1</li><li>2</li><li>3</li><li>4</li> </ul> 

there is a symbol with code 020h before "ul". 在“ ul”之前有一个代码为020h的符号。 I tryed: 我尝试过:

1) in the Test class: 1)在Test类中:

return writer.InnerWriter.ToString().Trim();

2) in the cshtml file: 2)在cshtml文件中:

@Html.Test().Trim()

3) Tryed to change writer settings 3)尝试更改作家设置

writer.InnerWriter.NewLine = string.Empty;
writer.NewLine = string.Empty;

But all these without positive result (third step partly clean the code). 但是所有这些都没有积极的结果(第三步部分清除了代码)。 Is here any way to have html code without tabs, spaces, end of string etc? 这是没有tab,空格,字符串结尾等的html代码的任何方法吗?

Trim() will only eliminate the leading and trailing spaces. Trim()仅消除前导和尾随空格。 Use .Replace(" ", string.empty) instead. 请改用.Replace(" ", string.empty)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM