I wrote an HtmlHelper extension to render Json+Ld script tags. The reason why I ask you for help is, the type attribute value "application/ld+json" is encoded and looks like "application/ld+json" and I could found a solution.
My C# code of the HtmlHelper:
public static IHtmlContent GetJsonLdScriptTag(this IHtmlHelper helper, string innerText)
{
//if(string.IsNullOrEmpty(innerText))
// return HtmlString.Empty;
var tag = new TagBuilder("script");
tag.MergeAttribute("type", "application/ld+json");
tag.InnerHtml.AppendHtml(innerText);
tag.TagRenderMode = TagRenderMode.Normal;
return tag;
}
In my view I use call the Html extension so:
@Html.GetJsonLdScriptTag("")
Html output is:
<script type="application/ld+json"></script>
I tried to decode by using HtmlDecode(...) and with returning Html.Raw(...) ;, but without success.
Another try was to return string instead IHtmlContent object, but this failed also.
public static string GetJsonLdScriptTag(this IHtmlHelper helper, string innerText)
{
//if(string.IsNullOrEmpty(innerText))
// return HtmlString.Empty;
var tag = new TagBuilder("script");
tag.MergeAttribute("type", "application/ld+json");
tag.InnerHtml.AppendHtml(innerText);
tag.TagRenderMode = TagRenderMode.Normal;
return tag.ToHtmlString();
}
public static string ToHtmlString(this IHtmlContent content)
{
using var writer = new IO.StringWriter();
content.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
Do you have an idea to handle this issue without hacks?
Best Tino
Looking at the source code , there doesn't seem to be any way to disable the encoding for an attribute value. It might be worth logging an issue to see if this could be added; but for the short term, you'll need to use something other than the TagBuilder
class.
private sealed class JsonLdScriptTag : IHtmlContent
{
private readonly string _innerText;
public JsonLdScriptTag(string innerText)
{
_innerText = innerText;
}
public void WriteTo(TextWriter writer, HtmlEncoder encoder)
{
writer.Write(@"<script type=""application/ld+json"">");
writer.Write(_innerText);
writer.Write("</script>");
}
}
public static IHtmlContent GetJsonLdScriptTag(this IHtmlHelper helper, string innerText)
=> new JsonLdScriptTag(innerText);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.