Using MVC 3 RTM I'm getting a strange NullReferenceException
:
@helper TestHelperMethod() {
var extra = "class=\"foo\"";
<div @Html.Raw(extra)></div>
}
It turns out that Html
(of type HtmlHelper
) is null
.
I've never seen this before in a regular view. I'm starting to experiment with declarative helper methods in Razor (so far they seem a little limited) and I'm quite stumped by what I'm seeing here.
I know it's not the point but if it is just
Html.Raw(value)
you were hoping to use when finding this question on Google (as I was) according to the source code of System.Web.Mvc.dll all Html.Raw does is:So I've just used
@(new HtmlString(value))
in my helper which works nicely.Just replace
with
I had the same issue and this line of code did the trick. It´s not a solution for using HtmlHelper, it's just a way of writing RAW html in a declarative razor helper.
Using Drew Noakes suggestion, I have come to a workaround that does the trick for now and that can be easily removed once the issue is solved in a newer version of MVC (that is if more stuff isn't changed that would break it:))
The goal is to be able to use an HtmlHelper inside a declarative helper method that lives in a file in App_Code without having a NullReferenceException. To solve this I included in all the files in App_Code the following:
This does seem to do the trick as I can now write the following helper (in the same file):
Obviously the helper method is just an example. This solution has the downside that the @functions declarations has to be introduced in all helper declaration files in App_Code, but does avoid complicating the call to the helper, as you can simply write in a view:
Hope this helps...
I think I know what's causing the issue...
The definition of the
Html
property getter is:Setting a breakpoint in my helper method shows that
CurrentPage
is not in fact an instance ofWebPage
, hence thenull
value.Here is the type hierarchy of
CurrentPage
(my class names doctored slightly):Note that the base class of my view has been specified in Web.config:
Which is defined both in generic and non-generic form:
So, if this problem does not occur for others, perhaps they're not using a custom
pageBaseType
.Note too that I've placed the
@helper
declaration inApp_Code\Helpers.cshtml
in the hope of making it globally accessible.Am I doing something wrong, or is this a bug?
EDIT Thanks Darin for pointing out this as a known issue. Still, why isn't the
Html
property redefined as:That's a known limitation of those helpers. One possibility is to pass it as parameter:
Another possibility is to write the helper as an extension method:
and then: