【问题标题】:Created an HtmlHelper Extension, but receive "Child actions are not allowed to perform redirect actions" exception创建了 HtmlHelper 扩展,但收到“不允许子操作执行重定向操作”异常
【发布时间】:2013-01-02 18:50:34
【问题描述】:

我创建了一个 HtmlHelper 扩展调用 ActionButton,它会输出一个 jQuery 按钮,该按钮将调用一个动作而不是使用 ActionLink。但是,我在下一行的扩展方法中收到了一个异常(它只是一个代码示例,会引发我看到的异常):

    MvcHtmlString str = helper.Action(actionName, controllerName, routeValues);

这是完整的方法,但使用 UrlHelper 创建操作 URL(对我有用)。我也有using System.Web.Mvcusing 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(...) 会引发异常。

谢谢!

【问题讨论】:

    标签: exception asp.net-mvc-4 extension-methods


    【解决方案1】:

    HtmlHelper.Action() 会立即调用你传递给它的 action 方法,并返回它的结果。
    这不是你想要的。

    您需要UrlHelper.Action(),它会返回操作的 URL。

    【讨论】:

    • 感谢您的澄清。尽管@Matti 也是正确的,但您解释了为什么它会引发异常。我错过了工具提示中说它将操作的 results 作为 MvcHtmlString 返回的部分。
    【解决方案2】:

    这是因为您调用的是helper.Action(即HtmlHelper)而不是urlHelper.Action

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多