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.

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.