jokul
jokul

Reputation: 1339

Retrieving generated ActionLink html from controller

I want to embed an action link in some text that will be stored in the database from my controller. I tried to accomplish this by instantiating a new HtmlHelper within the controller context:

//Controller
public ActionResult Foo()
{
    var x = ThemedActionLink(/*Parameters*/);
    //save x to database
    return View();
}

//Custom HtmlHelper code
private class EmptyViewDataContainer : IViewDataContainer
{
    public ViewDataDictionary ViewData { get; set; }
}

public static string ThemedActionLink(
    //Parameters
    )
{
    var helper = new HtmlHelper(new ViewContext(), new EmptyViewDataContainer());
    var preTheming = //Generate pre-element wrapper
    var postTheming = //Generate post-element wrapper
    return MvcHtmlString.Create(
        preTheming
        + helper.ActionLink(text, action, controller)
        + postTheming).ToString();
}

But I get NotImplementedException on the return statement. How can I get a correctly initialized HtmlHelper from the controller's context?

Upvotes: 1

Views: 42

Answers (1)

Tieson T.
Tieson T.

Reputation: 21191

Probably be easier to leverage TagBuilder and the UrlHelper property of the controller.

var a = new TagBuilder("a");
var url = Url.Action(action, controller);

a.InnerHtml(text);
a.Attributes.Add("href", url);

return MvcHtmlString.Create(preTheming + a.ToString() + postTheming);

I'd probably also leave off the last ToString() - it will get called implicitly at some point.

Upvotes: 1

Related Questions