I was getting error "NullReferenceException:..." at near the @Html.Raw(...
Hear is the code...
Commons.cshtml :
@helper BoxTitle(string CustomButtons)
{
if (!string.IsNullOrEmpty(CustomButtons))
{
@Html.Raw(CustomButtons)
}
}
view.cshtml :
<div class="box">
@Commons.BoxTitle("<button class='sub-button'>New</button>")
<div class="content">
</div>
</div>
Does anyone have a solution for this problem?
The default HtmlHelpers are not accessible in App_Code, which is where I assume Commons.cshtml is located.
You can work around this somewhat by taking the consuming WebViewPage as a parameter and using it to get to the HtmlHelpers. You'll also need to add a @using statement for System.Web.Mvc.Html.
Commons.cshtml :
@using System.Web.Mvc.Html
@helper BoxTitle(System.Web.Mvc.WebViewPage wvp, string CustomButtons)
{
if (!string.IsNullOrEmpty(CustomButtons))
{
@wvp.Html.Raw(CustomButtons)
}
}
view.cshtml :
<div class="box">
@Commons.BoxTitle(this, "<button class='sub-button'>New</button>")
<div class="content">
</div>
</div>
You can define a function inside the helper itself, and return MvcHtmlString, which is not encoded by default.
@functions
{
static MvcHtmlString Raw(string text)
{
return MvcHtmlString.Create(text);
}
}
@helper WriteSomeHtml()
{
@Raw("<p>some html</p>)
}
And you consume it in any helper with
@Raw("<p>your html</p>")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With