2013-01-02 19 views
0

我創建了一個HtmlHelper擴展調用ActionButton,它將吐出一個jQuery按鈕,它將調用一個操作而不是使用ActionLink。不過,我收到一個異常從以下行我的擴展方法中(它只是一個代碼示例,將提高我所看到的除外):創建一個HtmlHelper擴展,但收到「兒童行爲不允許執行重定向操作」異常

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(...)拋出一個例外。

謝謝!

回答

0

HtmlHelper.Action()將調用您立即傳遞的操作方法,並返回其結果。
這不是你想要的。

你想要UrlHelper.Action(),它返回一個URL到動作。

+0

謝謝您的澄清。雖然@Matti也是正確的,但你解釋了爲什麼會引發異常。我錯過了工具提示中的部分,它說它將操作的**結果**作爲MvcHtmlString返回。 – emgee

0

這是因爲你打電話helper.Action(即HtmlHelper)而不是urlHelper.Action

相關問題