我创建了一个HtmlHelper扩展名为ActionButton,它将生成一个jQuery按钮,该按钮将调用一个动作,而不是使用ActionLink。然而,我在下一行的扩展方法中收到了一个异常(这只是一个将引发我所看到的异常的代码示例):
MvcHtmlString str = helper.Action(actionName, controllerName, routeValues);
这是完整的方法,但使用UrlHelper来创建Action URL(这对我来说是有效的)。还有using System.Web.Mvc
和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;
}
我想知道为什么调用helper.Action(...)
会引发异常。
谢谢!
HtmlHelper.Action()
将立即调用您传递给它的操作方法,并返回其结果。
那不是你想要的。
您需要UrlHelper.Action()
,它返回一个URL给操作。
这是因为您调用的是helper.Action
(即HtmlHelper
)而不是urlHelper.Action
。