添加动作链接到由html帮助器MVC4生成的Html表

时间:2013-11-13 14:59:16

标签: asp.net-mvc asp.net-mvc-4

我有一个Htmlhelper扩展方法,可以从任何List<T>

生成一个Html表

我必须添加功能,使来自任何给定列的数据成为链接。

我创建了一个新类,其中包含创建链接所需的所有数据

  public class ColumnLinkDescription
  {
    //controller name
    public string Controller { get; set; }
    //Action name
    public string Action { get; set; }
    //parameter
    public string ID { get; set; }
  }

我还添加了一个方法,如果该列具有链接描述

,将尝试生成链接
    private static string TryGenerateLink<T>(HtmlHelper helper, T d, TableHeaderDetails h, string value)
    {
      if (h.Link != null)
      {
        var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
        var url = urlHelper.Action(h.Link.Controller,
        h.Link.Action,
        new { id = d.GetType().GetProperty(h.Link.ID) });
        value= url;
      }
      return value;
    }

以下列方式与我的桌面制作者联系:

      value= ((d.GetType().GetProperty(h.Name).GetValue(d, null)) ?? "").ToString();
      td.InnerHtml = TryGenerateLink<T>(helper, d, h, value);
      tr.InnerHtml += td.ToString();

我尝试了但是输出是:

<td class=" ">/ActionTest/ControllerTest/Int32%20ArticleCode</td>

使用定义:

new ColumnLinkDescription{Controller = "ControllerTest", Action="ActionTest", ID="ArticleCode"}

看起来我应该使用不同于urlHelper.Action的方法,我很难获得ArticleCode的值并将其作为参数添加到链接中。

EDIT1:

我通过TryGenerateLink()

中的简单修改得到了参数的值
var url = urlHelper.Action(h.Link.Controller, h.Link.Action, new { id = d.GetType().GetProperty(h.Link.ID).GetValue(d,null) });

输出:

<td class=" ">/ActionTest/ControllerTest/96776</td>

所以剩下的唯一问题是正确生成超链接

1 个答案:

答案 0 :(得分:1)

您不希望为此使用UrlHelper,因为正如您已经注意到的那样,UrlHelper.Action将创建相对URL但不会创建锚标记。你真正想要做的是利用HtmlHelper。这样,您就可以使用helper.ActionLink为您构建链接。