【问题标题】:Providing ID in ActionLink() or RouteLink()?在 ActionLink() 或 RouteLink() 中提供 ID?
【发布时间】:2011-12-12 17:21:10
【问题描述】:

我是 MVC 的新手,我想添加一个指向类似 ~/Destinations/35 的链接,它会引用 Destinations 控制器的 Index 视图,而 35 是要显示的目标的 ID。

ActionLink() 或 RouteLink() 似乎都不允许我创建这样的链接。

另外,我尝试过这样的事情:

<table>
@foreach (var d in ViewBag.Results)
{
    <tr>
        <td>
            @Html.ActionLink(
                String.Format("<b>{0}</b>", @Html.Encode(d.Title)),
                "Details", "Destinations")
        </td>
    </tr>
}
</table>

但我在 ActionLink 行上收到以下错误,我不明白。

“System.Web.Mvc.HtmlHelper”没有名为“ActionLink”的适用方法,但似乎具有该名称的扩展方法。扩展方法不能动态调度。考虑强制转换动态参数或调用扩展方法而不使用扩展方法语法。

有人可以帮我创建这个链接吗?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    您的代码的第一个问题是您试图在链接文本(&lt;b&gt; 标记)中使用 HTML,这是不可能的,因为根据设计它总是 HTML 编码。

    因此,假设您不希望链接中包含 HTML,您可以这样做:

    @Html.ActionLink(d.Title, "Details", "Destinations", new { id = "35" }, null)
    

    假设您需要在锚点内使用 HTML,您有两种可能性:

    1. 编写一个不会对文本进行 HTML 编码的自定义 ActionLink 助手(推荐),然后像这样使用:

      @Html.MyBoldedActionLink(d.Title, "Details", "Destinations", new { id = "35" }, null)
      
    2. 类似的东西:

      <a href="@Url.Action("Details", "Destinations", new { id = "35" })">
          <b>@d.Title</b>
      </a>
      

    由于我推荐第一种方法,这里是自定义帮助程序的示例实现:

    public static class HtmlExtensions
    {
        public static IHtmlString MyBoldedActionLink(
            this HtmlHelper htmlHelper,
            string linkText,
            string actionName,
            string controllerName,
            object routeValues,
            object htmlAttributes
        )
        {
            var anchor = new TagBuilder("a");
            anchor.InnerHtml = string.Format("<b>{0}</b>", htmlHelper.Encode(linkText));
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
            anchor.Attributes["href"] = urlHelper.Action(actionName, controllerName, routeValues);
            anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
            return new HtmlString(anchor.ToString());
        }
    }
    

    【讨论】:

    • +1 我还建议阅读一些关于 asp.net/mvc 的教程,因为这是基础知识
    • @Darin:谢谢!但是@Html.ActionLink(d.Title, "Details", "Destinations", new { id = "35" }, null) 行仍然给出了我在关于扩展方法不能动态调度的问题中引用的相同错误。我在这里搞砸了什么吗?
    • 看来我可以通过将动态值d.Title 类型转换为字符串来解决该错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    相关资源
    最近更新 更多