我写了一个基本的HtmlHelper。这是我编写的一个测试,它简化了我正在做的事情,并在我使用StringBuilder
和TagBuilder
对象时提供自我保证:
public static string HelloWorld(this HtmlHelper htmlHelper, string name)
{
var sb = new StringBuilder();
var builder = new TagBuilder("span");
builder.InnerHtml = "Hello, " + name + "!";
sb.Append(builder.ToString(TagRenderMode.Normal));
sb.Append("<br/>");
return sb.ToString();
}
此控件的输出对字符串进行编码,因此我看到以下内容:
<span>Hello, Jason!</span><br/>
在我看来,我使用以下内容:@Html.HelloWorld("Jason")
任何想法我可能做错了吗?
答案 0 :(得分:23)
Razor引擎默认在其呈现的任何字符串中转义HTML。如果您将返回类型更改为IHtmlString
,则不会发生这种情况。
public static IHtmlString HelloWorld(this HtmlHelper htmlHelper, string name)
...
return new HtmlString(sb.ToString());
}
答案 1 :(得分:3)
您的静态方法必须是HtmlString
而不是string
,并且您必须返回HtmlString(sb.ToString());
public static HtmlString HelloWorld(this HtmlHelper htmlHelper, string name)
{
var sb = new StringBuilder();
var builder = new TagBuilder("span");
builder.InnerHtml = "Hello, " + name + "!";
sb.Append(builder.ToString(TagRenderMode.Normal));
sb.Append("<br/>");
return new HtmlString(sb.ToString());
}
答案 2 :(得分:1)
使用AppendFormat
代替Append
var sb = new StringBuilder();
var builder = new TagBuilder("span");
builder.InnerHtml = "Hello, " + name + "!";
sb.AppendFormat(builder.ToString(TagRenderMode.Normal));
sb.AppendFormat("<br/>");
return sb.ToString();
答案 3 :(得分:0)
以下是使用.Net Core 2的2018年答案
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.IO;
public static IHtmlContent HelloWorld(this IHtmlHelper html, string name)
{
var span = new TagBuilder("span");
span.InnerHtml.Append("Hello, " + name + "!");
var br = new TagBuilder("br") {TagRenderMode = TagRenderMode.SelfClosing};
string result;
using (var writer = new StringWriter())
{
span.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default);
br.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default);
result = writer.ToString();
}
return new HtmlString(result);
}