Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @Html.Raw , ASP.NET, Razor @Helper

Tags:

c#

asp.net

razor

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?

like image 686
realgrid Avatar asked Dec 03 '25 09:12

realgrid


2 Answers

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>
like image 52
friggle Avatar answered Dec 05 '25 00:12

friggle


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>")
like image 24
Aleksandar Hocevar Avatar answered Dec 04 '25 23:12

Aleksandar Hocevar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!