【发布时间】:2015-08-08 08:17:27
【问题描述】:
我正在尝试扩展 Html.ActionLink,因为我想为共享组件(在本例中为模态)添加自定义元数据。
我的目标是进一步扩展 .Net MVC 中的 LinkExtensions 类,这将为 html 类属性添加一个值,并添加一个自定义数据属性,结果如下:
<a href="/Controller/Action/id" class="show-in-modal style1 style2" data-title="Modal title">Link</a>
帮助器看起来类似于 MVC 方法:
public static MvcHtmlString ModalLink(this HtmlHelper htmlHelper, string title, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
{
// Add 'show-in-modal' class here
// Add 'data-title' attribute here
return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes);
}
@Html.ModalLink("Modal title", "Link", "action", "controller", new { id = "id" }, new { @class = "style1 style2" });
我遇到的这个问题是我不能轻易修改 htmlAttributes 对象来添加我的类名和数据属性,这是有道理的,因为这是一个只读匿名对象。
有没有一种方法可以让我轻松应用所需的值/元数据,而无需通过反射将所有内容分开并重新组合在一起?
我注意到 MVC 具有接受 IDictionary<string, object> 形式的 html 属性的重载,是否有将匿名类型转换为可修改字典的扩展方法?
我在搜索中得到的只是如何使用 Html.ActionLink() 方法。
【问题讨论】:
-
为什么不创建自己的custom HTML helper
-
我正在尝试创建自己的助手......但我并没有重新发明轮子,而是试图利用已经完成 80% 工作的内置助手。正如我所说,我只需要附加到现有的
htmlAttributes参数。
标签: c# asp.net-mvc razor html-helper tagbuilder