2011-08-01 26 views
3

有沒有辦法在@helper聲明中訪問完整的@Url幫助對象?在@helper聲明中完成@Url助手

我想要做這樣的事情...

@helper Button(System.Web.Mvc.ActionResult action, string text) 
{ 
    <input type="button" name="btn" value="@text" onclick="windows.location='@Url.Action(action)'" /> 
} 

我發現this question但這種解決方案並不讓你訪問@Url.Action(ActionResult)。請注意我正在尋找的特定超載。

所以有沒有人想出了一個解決方案,這一個?我總是可以爲自定義助手做擴展方法風格,但我喜歡@helper風格,而且我已經遇到過幾次這個問題。

在預先感謝大家!

回答

3

有沒有辦法在@helper聲明中訪問完整的@Url輔助對象?

是的,通過將其作爲參數傳遞給輔助方法。

@helper Button(string action, string text, UrlHelper url) 
{ 
    <input type="button" name="btn" value="@text" onclick="windows.location='@url.Action(action)'" /> 
} 

,當你調用一些視圖助手:

@Button("someAction", "some text", Url) 
+0

好主意,但它不工作,或者我做錯了什麼。我嘗試了以下內容和操作方法,我得到的只有重載是採取行動的字符串名字的那些... '@helper ActionButton(System.Web.Mvc.ActionResult動作,字符串文本,系統。 Web.Mvc.UrlHelper URL) { }' – jrizzo

+0

@jrizzo,什麼重載的Action方法,不接受你正在談論的字符串? UrlHelper.Action方法沒有重載,它將'System.Web.Mvc.ActionResult'作爲我知道的第一個參數。你一定在嘗試錯誤。 –

+0

我正在尋找需要'ActionResult'的重載。 – jrizzo

0

我不知道的剃鬚刀,但對於HTML輔助當然可以。使用助手的RequestContext,如下所示。這裏是我爲ImageFor html helper寫的一個例子:

public static HtmlString ImageFor(this HtmlHelper helper, string url) 
    { 
     var urlHelper = new UrlHelper(helper.ViewContext.RequestContext); 
     TagBuilder tb = new TagBuilder("img"); 
     tb.MergeAttribute("src", urlHelper.Content(url)); 
     return new HtmlString(tb.ToString(TagRenderMode.SelfClosing)); 
    }