【问题标题】:Creating Html.ActionLink in C# string在 C# 字符串中创建 Html.ActionLink
【发布时间】:2013-11-15 21:58:27
【问题描述】:

我正在寻找一种通过 C# 生成Html.ActionLinks 的方法。

我该怎么做呢,我试过了:

public static string CreateSubjectTree(SqlConnection con)
{
    StringBuilder result = new StringBuilder();

    result.Append("Html.ActionLink(\"Blabla\", \"Read\", \"Chapter\")");

    return Convert.ToString(result);
}

这将返回原始的HTML,而不是生成的代码。

我希望它完成的是创建一个链接,该链接使用一些参数调用Controller

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 html.actionlink


    【解决方案1】:

    您不需要返回字符串。采取MvcHtmlString。像这样创建一个扩展方法:

    public static MvcHtmlString CustomActionLink( this HtmlHelper htmlHelper, SqlConnection con)
    {
        //do your retrival logic here
        // create a linktext string which displays the inner text of the anchor
        // create an actionname string which calls the controller
        StringBuilder result = new StringBuilder();
        result.Append(linktext);
        result.Append(actionname);
        return new MvcHtmlString(result);
    }
    

    在你看来:

    @Html.CustomActionLink(SqlConnection con)
    

    您需要导入命名空间 System.Web.Mvc.Html 并确保您的路由在 RouteConfig.cs 或您定义自定义路由的任何地方定义。

    重要提示:您返回的最终字符串(结果)需要采用以下格式:

    <a href='/Controller/Action/optionalrouteparameters'>LinkText</a>
    

    MvcHtmlString() 确保每个可能的字符,如 =, ? & \ 被正确转义并且链接被正确呈现

    参考见msdn:http://msdn.microsoft.com/en-gb/library/dd493018(v=vs.108).aspx

    【讨论】:

      【解决方案2】:
      using System.Web.Mvc.Html;
      
      namespace MyHelper
      {
              public static class CustomLink
              {
                  public static IHtmlString CreateSubjectTree(this HtmlHelper html, SqlConnection con)
                  {
                      // magic logic
                      var link = html.ActionLink("Blabla", "Read", "Chapter").ToHtmlString();          
                      return new MvcHtmlString(link);
                  }
      
              }
      }
      
          Use in View:
           @Html.CreateSubjectTree(SqlConnection:con)
      

      网络配置:

       <system.web.webPages.razor>
         ...
          <pages pageBaseType="System.Web.Mvc.WebViewPage">
            <namespaces>
              <add namespace="MyHelper" />
             ...
            </namespaces>
          </pages>
        </system.web.webPages.razor>
      

      【讨论】:

        【解决方案3】:

        Html.ActionLink 的重载已经可以满足您的需求:

        @Html.ActionLink("Link text", "action", "controller", new { id = something }, null)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-11-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-29
          • 1970-01-01
          • 1970-01-01
          • 2011-11-13
          相关资源
          最近更新 更多