c# - Html.ActionLink 扩展

标签 c# asp.net-mvc razor html-helper tagbuilder

我正在尝试扩展 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() 方法。

最佳答案

您要查找的函数是:

HtmlHelper.AnonymousObjectToHtmlAttributes()

https://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.anonymousobjecttohtmlattributes(v=vs.118).aspx

这是 ModalLink 扩展的一个版本:

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

  var htmlAttr = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

  const string classKey = "class";
  const string titleKey = "data-title";

  const string classToAdd = "show-in-modal";
  if (htmlAttr.ContainsKey(classKey) == true)
  {
    htmlAttr[classKey] += " " + classToAdd;
  }
  else
  {
    htmlAttr.Add(classKey, classToAdd);
  }

  if (htmlAttr.ContainsKey(titleKey) == true)
  {
    htmlAttr[titleKey] = title;
  }
  else
  {
    htmlAttr.Add(titleKey, title);
  }

  return htmlHelper.ActionLink(linkText, actionName, controllerName, new RouteValueDictionary(routeValues), htmlAttr);
}

关于c# - Html.ActionLink 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30462243/

相关文章:

c# - 自定义类型 GetHashCode

asp.net - 为什么混合使用 Razor Pages 和 VueJs 是一件坏事?

c# - 为防止由于添加事件句柄而导致内存泄漏而采取的预防措施

c# - 如何使用 LINQ 对多个字段进行排序?

asp.net-mvc - 如何选择下拉列表值并在mvc3中显示?

c# - 导出到 Excel .xlsx 文件

asp.net - 如何使用 IIS 7.5 压缩来自 ASP.NET MVC 的 Json 结果

jquery - 将脚本文件添加到 MVC4 应用程序和 _Layout.cshtml 混淆

html - 如何根据 ViewModel 的值启用/禁用按钮?

c# - 我可以将 Windows Identity Foundation 3.5 与 .NET 4.5 一起使用吗?