C# 如何在ActionLink的字符串部分添加新行字符?

C# 如何在ActionLink的字符串部分添加新行字符?,c#,asp.net,asp.net-mvc,actionlink,C#,Asp.net,Asp.net Mvc,Actionlink,我正在用C#构建一个Ajax.ActionLink,它开始于: <%= Ajax.ActionLink("f lastname", ...more stuff 试试这个: <%= Ajax.ActionLink("f<br />lastname", ...more stuff 您不能使用,因为ActionLink方法(事实上我相信所有html和ajax扩展方法)都对字符串进行编码。因此,输出类似于 <a href="...">f&lt;br /&a

我正在用C#构建一个Ajax.ActionLink,它开始于:

<%= Ajax.ActionLink("f lastname", ...more stuff
试试这个:

<%= Ajax.ActionLink("f<br />lastname", ...more stuff

您不能使用

,因为ActionLink方法(事实上我相信所有html和ajax扩展方法)都对字符串进行编码。因此,输出类似于

<a href="...">f&lt;br /&gt;lastname</a>

您可以尝试使用以下格式:

<%= string.Format(Ajax.ActionLink("f{0}lastname", ...more stuff), "<br />") %>

过去为我工作的
\n
。但现在,它似乎被抹黑了。也可以使用换行符方法,例如:

string jay = "This is a" + Environment.NewLine + "multiline" + Environment.NewLine + "statement";

您是否尝试了\r\n组合?

您可能需要恢复到执行以下操作:

<a href="<%= Url.Action("action") %>">f<br />last</a>
public static class CustomHtmlHelperExtensions
{
    public static MvcHtmlString FormattedActionLink(this HtmlHelper html, ...)
    {
        var tagBuilder = new TagBuilder("a");

        // TODO : Implementation here

        // this syntax might not be exact but you get the jist of it!
        return MvcHtmlString.Create(tagBuilder.ToString());
    }
}

然后手动连接Ajax位。

怎么样:

<%= Server.UrlDecode(Ajax.ActionLink(Server.UrlEncode("f<br/>lastname"), ...more stuff
这对我很有用-

<%= HttpUtility.HtmlDecode(Html.ActionLink("AOT &lt;br/> Claim #", "actionName" ))%>

我认为安德鲁·黑尔的答案是正确的。如果您有稍微复杂一点的需求,您可以选择创建自己的AjaxHelper或HtmlHelper。这将涉及创建在AjaxHelper和HtmlHelper上工作的自定义扩展方法,方法如下:

<a href="<%= Url.Action("action") %>">f<br />last</a>
public static class CustomHtmlHelperExtensions
{
    public static MvcHtmlString FormattedActionLink(this HtmlHelper html, ...)
    {
        var tagBuilder = new TagBuilder("a");

        // TODO : Implementation here

        // this syntax might not be exact but you get the jist of it!
        return MvcHtmlString.Create(tagBuilder.ToString());
    }
}
您可以使用dotPeek或您最喜欢的.NET反射工具来检查ASP.NET MVC(例如ActionLink)等附带的标准扩展,以了解Microsoft是如何实现这些扩展方法的。他们有一些很好的写作模式。在过去,我采用这种方法以可读的方式简化HTML输出,例如,对于Google Maps或Bing Maps集成,用于创建
ActionImage
等选项,例如
@HTML.ActionImage(…)
,或者通过启用
@HTML.Textile>等语法来集成输出纺织品格式化HTML(“纺织品格式字符串”)

如果您在单独的程序集中定义了它(就像我一样),那么请记住将其包含到项目引用中,然后将其添加到项目的Web.config中


很明显,这种方法对于您的特定目的来说是过分的,因此,我投票支持Andrew Hare针对您的具体案例的方法。

问题提出已经好几年了,但我遇到了问题。我发现答案是(在MVC中):

ActionLink中的文本:…ActionLink(“TextLine1”+环境。换行符+“TextLine2”

在ActionLink中,有一个指向css的类,该类具有以下行:

空白:pre


就是这样。我已经看到了答案,他们将整个Actionline放在
标记中,但这导致了比解决问题更多的问题。

该死的不起作用。这给我带来了一个--“System.Web.HttpCompileException未处理,用户代码错误CS1010:Newline in constant“嗯,尝试使用.Replace而不是string.format吗?我还没有真正使用过ajax扩展,所以我不知道其他方法可以做到这一点。这些天你可能不得不将其包装在@Html.Raw中。