c# - 如何将 span 元素放入 ActionLink MVC3 中?

标签 c# asp.net .net asp.net-mvc-3 razor

如何在 ActionLink 中放置一个 span 元素,但不使用 URL.ACTION?

这个:

 <li><span>
     @Ajax.ActionLink("LinkText", "ControllerName", new AjaxOptions
                 {
                     UpdateTargetId = "div",
                     InsertionMode = InsertionMode.Replace,
                     HttpMethod = "GET",
                     LoadingElementId = "progress"

                 })
 </span></li>

生成这个:

<li>
<span>
<a href="/Home/ControllerName" data-ajax-update="#scroll" 
 data-ajax-mode="replace" data-ajax-method="GET" 
 data-ajax-loading="#progress" data-ajax="true">LinkText</a>
</span>
</li>

但我还需要别的东西。如何创建生成此输出的自定义 MVC3 ActionLink 方法:

<li>
    <a href="/Home/ControllerName" data-ajax-update="#scroll" 
     data-ajax-mode="replace" data-ajax-method="GET" 
     data-ajax-loading="#progress" data-ajax="true">

     <span>LinkText</span> // this span generated inside <a>

    </a>
</li>

最佳答案

How to put span element inside ActionLink BUT NOT WITH URL.ACTION

简单的回答:你不能。 ActionLink 方法 HTML 对链接文本进行编码,您对此无能为力(您可以在 Microsoft 开张票,以便他们提供允许您在 ASP.NET MVC vNext 中执行此操作的重载)。

目前您可以编写一个不会编码的自定义 html 帮助程序:

public static class AjaxExtensions
{
    public static IHtmlString MyActionLink(
        this AjaxHelper ajaxHelper,
        string linkText,
        string actionName,
        AjaxOptions ajaxOptions
    )
    {
        var targetUrl = UrlHelper.GenerateUrl(null, actionName, null, null, ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, true);
        return MvcHtmlString.Create(ajaxHelper.GenerateLink(linkText, targetUrl, ajaxOptions ?? new AjaxOptions(), null));
    }

    private static string GenerateLink(
        this AjaxHelper ajaxHelper, 
        string linkText, 
        string targetUrl, 
        AjaxOptions ajaxOptions, 
        IDictionary<string, object> htmlAttributes
    )
    {
        var a = new TagBuilder("a")
        {
            InnerHtml = linkText
        };
        a.MergeAttributes<string, object>(htmlAttributes);
        a.MergeAttribute("href", targetUrl);
        a.MergeAttributes<string, object>(ajaxOptions.ToUnobtrusiveHtmlAttributes());
        return a.ToString(TagRenderMode.Normal);
    }
}

然后:

@Ajax.MyActionLink(
    "<span>LinkText</span>", 
    "ActionName", 
    new AjaxOptions {
        UpdateTargetId = "div",
        InsertionMode = InsertionMode.Replace,
        HttpMethod = "GET",
        LoadingElementId = "progress"
    }
)

关于c# - 如何将 span 元素放入 ActionLink MVC3 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8518109/

相关文章:

c# - 无法将整数类型隐式转换为 bool 值

c# - 正则表达式匹配完成后删除字符串的不匹配部分 - c#

c# - Asp.net 呈现编码错误的字符串,但 PHP 不呈现 (MySQL)

.net - OO 模式 : Shared work between abstract base class and subclasses

c# - 从析构函数调用 BeginInvoke

c# - aspnet_Membership 表中有解密密码的方法吗?

c# - Windows 窗体图片框不能可靠地刷新

asp.net - 我如何制作一个类似于 superuser.com 上的 beta 访问页面?

Asp.net 错误无法加载文件或程序集

c# - C# WinForm中如何根据不同选项设计设置UI?