I created an HtmlHelper extension call ActionButton which will spit out a jQuery button that will call an action rather than using ActionLink. However, I receive an exception from within my extension method on the following line (it’s just a sample of code that will raise the exception I was seeing):
MvcHtmlString str = helper.Action(actionName, controllerName, routeValues);
Here’s the full method but using UrlHelper to create the Action URL (which works for me). I also have using System.Web.Mvc and using System.Web.Mvc.Html.
public static HtmlString ActionButton(this HtmlHelper helper, string linkText, string actionName, string controllerName, object routeValues)
{
TagBuilder tag = new TagBuilder("a");
UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
tag.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
// the next line causes the exception, not really being used other than to
// raise the exception and illustrate the call I was making
MvcHtmlString str = helper.Action(actionName, controllerName, routeValues);
tag.MergeAttribute("rel", "external");
tag.MergeAttribute("data-role", "button");
tag.MergeAttribute("data-mini", "true");
tag.MergeAttribute("data-inline", "true");
tag.MergeAttribute("data-icon", "arrow-r");
tag.MergeAttribute("data-iconpos", "right");
tag.MergeAttribute("data-theme", "b");
tag.SetInnerText(linkText);
HtmlString html = new HtmlString(tag.ToString(TagRenderMode.Normal));
return html;
}
I would like to know why calling helper.Action(...) raises an exception.
Thanks!
HtmlHelper.Action()will call the action method you pass it immediately, and return its results.That’s not what you want.
You want
UrlHelper.Action(), which returns a URL to the action.