我有一个函数可以重载 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"。它用下划线呈现。我想知道为什么会这样,是否没有办法转换它?
请您参考如下方法:
您只需要通过HtmlHelper.AnonymousObjectToHtmlAttributes 传递htmlAttributes 对象即可。而不是使用提供的 RouteValueDictionary 构造函数。
来自 MSDN:
Return Value
Type: System.Web.Routing.RouteValueDictionary
The HTML attributes with underscore characters replaced by hyphens.
