asp.net-mvc - 附加到 HtmlHelper 扩展方法中的routeValues

标签 asp.net-mvc asp.net-mvc-3 html-helper

我想创建一个简单的 HtmlHelper.ActionLink 扩展,将值添加到路由值字典中。这些参数与 HtmlHelper.ActionLink 相同,即:

public static MvcHtmlString FooableActionLink(
    this HtmlHelper html,
    string linkText,
    string actionName,
    string controllerName,
    object routeValues,
    object htmlAttributes)
{
  // Add a value to routeValues (based on Session, current Request Url, etc.)
  // object newRouteValues = AddStuffTo(routeValues);

  // Call the default implementation.
  return html.ActionLink(
      linkText, 
      actionName, 
      controllerName, 
      newRouteValues, 
      htmlAttributes);
}

我添加到 routeValues 的逻辑有些冗长,因此我希望将其放入扩展方法助手中,而不是在每个 View 中重复它。

我有一个似乎有效的解决方案(作为下面的答案发布),但是:

  • 对于如此简单的任务来说,似乎没有必要那么复杂。
  • 所有的转换都让我觉得脆弱,就像在某些边缘情况下我会导致 NullReferenceException 或其他情况。

请发布任何改进建议或更好的解决方案。

最佳答案

public static MvcHtmlString FooableActionLink(
    this HtmlHelper html,
    string linkText,
    string actionName,
    string controllerName,
    object routeValues,
    object htmlAttributes)
{
    // Convert the routeValues to something we can modify.
    var routeValuesLocal =
        routeValues as IDictionary<string, object>
        ?? new RouteValueDictionary(routeValues);

    // Convert the htmlAttributes to IDictionary<string, object>
    // so we can get the correct ActionLink overload.
    IDictionary<string, object> htmlAttributesLocal =
        htmlAttributes as IDictionary<string, object>
        ?? new RouteValueDictionary(htmlAttributes);

    // Add our values.
    routeValuesLocal.Add("foo", "bar");

    // Call the correct ActionLink overload so it converts the
    // routeValues and htmlAttributes correctly and doesn't 
    // simply treat them as System.Object.
    return html.ActionLink(
        linkText,
        actionName,
        controllerName,
        new RouteValueDictionary(routeValuesLocal),
        htmlAttributesLocal);
}

关于asp.net-mvc - 附加到 HtmlHelper 扩展方法中的routeValues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9130309/

相关文章:

css - 水平 JQuery UI slider

asp.net-mvc - 使用 ASP.NET MVC 查询字符串中的身份验证 token 对用户进行身份验证

asp.net-mvc - 如何在 ASP.NET MVC 中定义表单字段前缀

asp.net-mvc - ASP.net MVC 3-在OnActionExecuting中获取发布的JSON数据

asp.net-mvc - 通过 ajax 发送请求时自动呈现部分

asp.net-mvc - 使用模型和 htmlhelper 渲染部分 View

ruby-on-rails - Rails View 助手未将 HTML 插入页面

c# - 何时在 ASP.NET MVC 中实例化 EF4 上下文?

asp.net-mvc - 处理 View 和模型之间的多个请求的最佳 MVC 方式

c# - 在 View 中使用 expando 对象?