过去,在以前版本的MVC中,在Razor Views中需要一个nl到br功能,我曾经实现了以下nl到br HTML帮助器:
public static class FormatingHelpers
{
public static MvcHtmlString Nl2Br(this HtmlHelper htmlHelper, string text)
{
if (string.IsNullOrEmpty(text))
return MvcHtmlString.Create(text);
else
{
StringBuilder builder = new StringBuilder();
string[] lines = text.Split('\n');
for (int i = 0; i < lines.Length; i++)
{
if (i > 0)
builder.Append("<br/>");
builder.Append(HttpUtility.HtmlEncode(lines[i]));
}
return MvcHtmlString.Create(builder.ToString());
}
}
}
现在我尝试使用ASP.NET Core MVC
,但它不起作用,MvcHtmlString
类不存在。
事实上,我认为HTML助手甚至不再存在,取而代之的是标签助手。
无论如何,这个Nl2Br
功能如何与ASP.NET Core MVC
实现?
答案 0 :(得分:2)
HTML帮助程序仍然存在,但是对于这个问题,TagHelpers确实在ASP.NET Core中使用。您可以简单地创建自己的自定义TagHelper,例如:
public class Nl2BrTagHelper : TagHelper
{
//Set this as <nl2br text=
public string Text { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "div"; // Replaces <nl2br> with <div> tag
StringBuilder builder = new StringBuilder();
string[] lines = Text.Split('\n');
for (int i = 0; i < lines.Length; i++)
{
if (i > 0)
builder.Append("<br/>");
builder.Append(HttpUtility.HtmlEncode(lines[i]));
}
output.Content.SetContent(builder.ToString());
}
}
请根据自己的需要进行调整。有关创作自己的标签助手的更多信息,请访问:https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/authoring
答案 1 :(得分:0)
非常类似于Danny van der Kraan的建议,对ASP.NET Core 1.1略有改动
using System.Net;
using System.Text;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace AppName.TagHelpers
{
[HtmlTargetElement("nl2br", Attributes = "text")]
public class Nl2brTagHelper : TagHelper
{
[HtmlAttributeName("text")]
public string Text { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = string.Empty;
StringBuilder builder = new StringBuilder();
string[] lines = Text.Split('\n');
for (int i = 0; i < lines.Length; i++)
{
if (i > 0)
{
builder.Append("<br/>");
}
builder.Append(WebUtility.HtmlEncode(lines[i]));
}
output.Content.SetHtmlContent(builder.ToString());
}
}
}