2012-07-18 70 views
3

我有一個@heper pagination函數。這是有兩個查看幫手ViewBagUrl。 這個分頁會被這麼多頁面使用,所以我將Views文件夾 的代碼移動到App_Code文件夾。裏面的代碼App_Code/Helper.cshtml將@helper代碼移動到App_Code文件夾拋出錯誤

@helper buildLinks(int start, int end, string innerContent) 
{ 
    for (int i = start; i <= end; i++) 
    { 
     <a class="@(i == ViewBag.CurrentPage ? "current" : "")" href="@Url.Action("index", "country", new { page = i })">@(innerContent ?? i.ToString())</a> 
    } 
} 

但現在當我運行的應用程序。它會拋出錯誤

error CS0103:The name 'ViewBag' does not exist in the current context 
error CS0103:The name 'Url' does not exist in the current context 

是否需要導入任何命名空間或問題出在哪裏?

我想要做的方式是完美的嗎?

回答

4

正如馬克說,你應該通過UrlHelper作爲參數傳遞給你的助手:

@helper buildLinks(int start, int end, int currentPage, string innerContent, System.Web.Mvc.UrlHelper url) 
{ 
    for (int i = start; i <= end; i++) 
    { 
     <a class="@(i == currentPage ? "current" : "")" href="@url.Action("index", "country", new { page = i })">@(innerContent ?? i.ToString())</a> 
    } 
} 

,然後調用它像這樣FOMR一個觀點:

@Helper.buildLinks(1, 10, ViewBag.CurrentPage, "some text", Url) 
+0

Darin,爲什麼我要傳遞Url,如果我可以從RequestContext中提取它,就像我在@ akakey的回覆中發佈的評論一樣? – ekkis 2013-12-22 23:38:13

+0

我不想將currentPage作爲參數傳遞。 @akakey找到了更好的。 – Neshta 2014-09-17 05:59:25

+0

請參閱下面的@akakey答案,它應該被標記爲正確答案 – 2017-11-21 17:13:24

4

如果您將幫助者移至App_Code,那麼您必須將ViewBag,UrlHelper,HtmlHelper通過視圖中的函數。

Ex。在App_Code文件

@helper SomeFunc(System.Web.Mvc.HtmlHelper Html) 
{ 
    ... 
} 

從您的視圖

的HTML幫助功能,

@SomeFunc("..", Html) // passing the html helper 
+0

我可以用'using'關鍵字在頁面頂部? ?? – 2012-07-18 05:04:59

+0

是的,你可以使用它,但你必須從查看 – VJAI 2012-07-18 05:18:15

+0

通過的助手,你可以顯示一個小的兩行代碼嗎? – 2012-07-18 05:20:34

12

那麼實際上你可以從助手訪問ViewBag App_Code文件夾裏面是這樣的:

@helper buildLinks() 
{ 
    var p = (System.Web.Mvc.WebViewPage)PageContext.Page; 

    var vb = p.ViewBag; 

    /* vb is your ViewBag */ 
} 
+0

這個答案是最乾淨的。我不知道爲什麼它沒有被選中。爲了完整性,可以像下面這樣訪問@Url:http://stackoverflow.com/questions/4522807/how-do-i-use-urlhelper-from-within-a-razor-helper – ekkis 2013-12-22 23:36:42

+0

完美!非常感謝! – Neshta 2014-09-17 06:00:24

相關問題