3

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?

realgrid
  • 31
  • 1
  • 2

2 Answers2

2

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>
friggle
  • 3,362
  • 3
  • 35
  • 47
1

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>")