【问题标题】:Overloading ActionLink in MVC and htmlAttributes在 MVC 和 htmlAttributes 中重载 ActionLink
【发布时间】:2023-03-03 01:41:01
【问题描述】:

我有一个重载 actionlink 的函数,只需将一个新参数添加到路由值“ID”,我在各处都在使用它。

到目前为止,这是我的代码:

public static MvcHtmlString ReportActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
{
    RouteValueDictionary routeValueDictionary = new RouteValueDictionary(routeValues);
    routeValueDictionary.Add("id", HttpContext.Current.Request.RequestContext.RouteData.Values["id"]);

    IDictionary<string, object> attrs = new RouteValueDictionary(htmlAttributes);

    return helper.ActionLink(linkText, actionName, controllerName, routeValueDictionary, attrs);        
}

如您所见,我传入了 routeValues,将它们转换为字典并添加我的 ID。

当我将我的 htmlAttributes 转换为 IDictionary 时会出现问题,因为重载的方法期望它不会替换我的属性中的下划线,即

data_event = "something" 不会像匿名类型那样变成 data-event = "something"。它使用下划线呈现。我想知道这是为什么,如果没有办法转换它?

【问题讨论】:

  • 能否添加一个 ReportActionLink 调用的示例?

标签: c# asp.net-mvc


【解决方案1】:

您只需要通过HtmlHelper.AnonymousObjectToHtmlAttributes 传递htmlAttributes 对象,而不是使用提供的RouteValueDictionary 构造函数。

来自 MSDN:

返回值
类型:System.Web.Routing.RouteValueDictionary
下划线字符替换为连字符的 HTML 属性。

【讨论】:

  • 谢谢!这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 2012-02-11
  • 1970-01-01
  • 2013-08-06
  • 2011-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
相关资源
最近更新 更多