收录日期:2020/06/02 03:22:31 时间:2011-12-28 08:08:34 标签:c#,asp.net,asp.net-mvc,actionlink

I'm building a Ajax.ActionLink in C# which starts:

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

and I'd like there to be a new line character between the words "f" and "lastname". How can I accomplish this? I thought the special character was \n but that doesn't work, and <br> doesn't work either.

You might have to revert to doing something like:

<a href="<%= Url.Action("action") %>">f<br />last</a>

And then wire in the Ajax bits manually.

Try this:

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

You can't use <br /> because the ActionLink method (and indeed I believe all the html and ajax extension methods) encode the string. Thus, the output would be something like

<a href="...">f<br />lastname</a>

What you could try instead would be a formatting:

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

Did you try the \r\n combination?

How about:

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

This works for me -

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

The \n used to work for me. But now it seems to be depricated. Alternitavely, you may use the NewLine method, for example:

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

I think Andrew Hare's answer is correct. If you have slightly more complicated requirement, you do have the option to create your own AjaxHelper or HtmlHelper. This will involve creating custom extension methods that work on AjaxHelper and HtmlHelpers, by doing something like:

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());
    }
}

You can use dotPeek or your favorite .NET reflection tool to examine the standard extensions that come with ASP.NET MVC (e.g., ActionLink) etc to find how Microsoft has implemented most of those extension methods. They have some pretty good patterns for writing those. In the past, I have taken this approach to simplify outputting HTML in a readable manner, such as, for Google Maps or Bing Maps integration, for creating options like ActionImage e.g., @Html.ActionImage(...) or to integrate outputting Textile-formatting HTML by enabling syntax such as @Html.Textile("textile formatted string").

If you define this in a separate assembly (like I do), then remember to include this into your project references and then add it to the project's Web.config as well.

Obviously, this approach is overkill for your specific purposes, and for this reason, my vote is for Andrew Hare's approach for your specific case.