在previous post我問了一個關於幫助者入門的問題。我成功了,但是當我嘗試使用該技術時1.要編寫基於Html.RenderAction的另一個幫助程序,以及2.要傳入我自己的自定義幫助程序,一旦將它們導出到App_Code,就會收到錯誤。MVC4 URLHelper正在工作,但HTMLHelper沒有。我在做什麼錯
再次強調,它們以內聯方式工作,但不在導出到App_Code時工作。
這裏是原代碼:
我的代碼很多地方都只有以下幾點:
<section class="Box">
@{ Html.RenderAction("PageOne"); }
</section>
其他許多地方都有這樣的:
@if (@Model.PageTwo)
{
<section class="Box">
@{ Html.RenderAction("PageTwo"); }
</section>
}
所以我的第一個步驟是將以下內容提取到內聯助手中,可用於上述所有代碼塊中:
@helper Item(HtmlHelper html, string action, string htmlClass)
{
<section class="@htmlClass">
@{ html.RenderAction(action); }
</section>
}
助手上面讓我來代替,看起來像在第一代碼段上面這行的所有代碼塊:
@Item(Html, "PageOne", "Box")
然後我接着寫第二個輔助看起來像這樣:
@helper Item(HtmlHelper html, string action, string htmlClass, bool test)
{
if (test)
{
@Item(html, action, htmlClass)
}
}
此助手可以讓我代替所有的代碼塊看起來像第二個代碼段上面這條線:
@Item(Html, "PageTwo", "Box", @Model.ShowThisTorF)
我的主要問題再次是,這工作內聯,所以爲什麼不當我把它刪除到App_Code。
一旦我將它移動到App_Code文件我得到以下錯誤: 第一個問題是關於增加一個使用引用(因爲的HtmlHelper不明確),而我添加以下代碼行:
@using HtmlHelper=System.Web.Mvc.HtmlHelper
這刪除第一個錯誤,但後來我得到另一個錯誤:
System.Web.Mvc.HtmlHelper does not contain a definition for 'RenderAction' and no extension method 'RenderAction' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)
我也嘗試過其他的參考,但沒有結果:
@using HtmlHelper=System.Web.WebPages.Html.HtmlHelper
我遇到的另一個問題是,我不認爲第二個塊會工作,一旦我得到第一個工作。即使它內聯運行良好。
另外,我知道它很明顯,但如果我不在這裏說,有人會在他們的答案中提出。
@Helpers.Item(Html, "PageOne", "Box")
@Helpers.Item(Html, "PageTwo", "Box", @Model.ShowThisTorF)
感謝任何與此幫助:當我把它輸出到文件App_Code文件的要求,所以一行代碼塊看起來像我確實添加文件名前綴。
感謝您的回答。我教過它可能只是微小的變化。非常感激。 – 2013-02-13 12:46:29