在MVC和htmlAttributes中重载ActionLink

时间:2013-01-18 05:41:24

标签: c# asp.net-mvc

我有一个重载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”。它以下划线呈现。我想知道为什么会这样,如果没有办法转换呢?

1 个答案:

答案 0 :(得分:4)

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

来自MSDN:

  

返回值
  输入:System.Web.Routing.RouteValueDictionary
  带有下划线字符的HTML属性替换为连字符。

相关问题