Michael Tot Korsgaard
Michael Tot Korsgaard

Reputation: 4014

Creating Html.ActionLink in C# string

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.

Upvotes: 0

Views: 5084

Answers (3)

Ilya Sulimanov
Ilya Sulimanov

Reputation: 7836

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>

Upvotes: 2

Marco
Marco

Reputation: 23927

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

Upvotes: 3

John H
John H

Reputation: 14655

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

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

Upvotes: 1

Related Questions