0

I'm looking for a way to generate Html.ActionLinks through C#.

How would I go and do this, I've tried this:

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

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

    return Convert.ToString(result);
}

This returns the raw HTML rather than the generated code.

What I want it to accomplish is creating a link which calls the Controller with some parameters.

tereško
  • 58,060
  • 25
  • 98
  • 150
Michael Tot Korsgaard
  • 3,892
  • 11
  • 53
  • 89

3 Answers3

3

You do not need to return a string. Take a MvcHtmlString. Create an extension method like this:

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);
}

In your view:

@Html.CustomActionLink(SqlConnection con)

You need to import the namespace System.Web.Mvc.Html AND make sure your route is defined in the RouteConfig.cs or whereever you define your custom routes.

An Important note: Your final string (result), which is returned needs to be in the format:

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

The MvcHtmlString() makes sure every possible character like =, ? & \ are properly escaped and the link is rendered correctly

For reference see msdn: http://msdn.microsoft.com/en-gb/library/dd493018(v=vs.108).aspx

Marco
  • 22,856
  • 9
  • 75
  • 124
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)

Web config:

 <system.web.webPages.razor>
   ...
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="MyHelper" />
       ...
      </namespaces>
    </pages>
  </system.web.webPages.razor>
Ilya Sulimanov
  • 7,636
  • 6
  • 47
  • 68
1

There's an overload of Html.ActionLink that already does what you want:

@Html.ActionLink("Link text", "action", "controller", new { id = something }, null)
John H
  • 14,422
  • 4
  • 41
  • 74