Custom HTML Helpers in Razor & HTML Extension Methods
There are a lot of questions, here 开发者_C百科and everywhere, regarding the impossibility of using HtmlHelper extension methods (like ActionLink) in an @helper (razor) method. Right now, in my project, I solved the problem passing as an extra parameter the current page (System.Web.Mvc.WebViewPage page) to the @helper, like in
@helper HelperFunction(SampleParameter sp, System.Web.Mvc.WebViewPage page)
and using it (trivially) as in
{
...
@page.Html.ActionLink("Title", "Action")
...
}
I would like to know if it's too stupid :-), and why. It would be better, of course, to have direct access to the current HtmlHelper of the page where the @helper is called, but, anyway... if this a good solution...
Andrea
I was curious why this didn't work, so I had a little look.
When you put code into the App_Code folder, it inherits from System.Web.WebPages.HelperPage
and although this has a Html
property, it's a System.Web.WebPages.HtmlHelper
and not a System.Web.Mc.HtmlHelper
, which is why you can't find things like ActionLink on it :(
I had a quick look around, and found this answer from Andrew Nurse:
Omar's got the right answer here, but I wanted to add something (do feel free to mark Omar's response as the answer).
We were aware of this in v1 and weren't able to get a great fix in the product, but David Ebbo (an architect on the ASP.Net team) posted a sample of a Visual Studio Code Generator that is basically a first exploration of the kind of ideas we're looking at to make this work properly: http://blogs.msdn.com/b/davidebb/archive/2010/10/27/turn-your-razor-helpers-into-reusable-libraries.aspx
Try that out and see what you think! Let David know if you have comments by posting on his blog.
Unfortunately, it looks like you can't even put the Helper outside of App_Code into your Layout class or _ViewStart :(
精彩评论