BENBUN Coder
BENBUN Coder

Reputation: 4881

MVC @helper error with HTML.Raw

I have the following code in a Razor Helper file

@helper MakeNoteBlank(string content)
{
    string msg = "";

    if(content == null)
    {
        msg = " ";
    }
    else
    {
        msg = content;
    }

    <div class="note">
        <p>
             @Html.Raw(msg)
        </p>
    </div>
}

The code fails at execution with the @Html.Raw(..) statement, stating that "Object reference not set to an instance of an object."

If I remove the @Html.Raw(..) and output 'msg' directly then there is no problem.

What am I doing wrong?

Upvotes: 10

Views: 3577

Answers (2)

Babak
Babak

Reputation: 1344

The best approach I can think of would possibly be creating an extension method for HtmlHelper. You need to create a class like this:

using System.Web;
using System.Web.Mvc;

namespace MyApplication.Extensions
{
    public static class HtmlHelperExtension
    {
        public static IHtmlString DisplayMessage<T>(this HtmlHelper<T> htmlHelper, string content)
        {
            return htmlHelper.Raw($@"
                <div class=""note"">
                  <p>
                     {content ?? "&nbsp;"}
                  </p>
                </div>
            ");
        }
    }
}

Then in your cshtml file, simply use it like this:

@using MyApplication.Extensions;

@Html.DisplayMessage("Your content here")

Hope this helps.

Upvotes: 0

Ravi Rajan
Ravi Rajan

Reputation: 426

use @(new HtmlString()) instead of @Html.Raw()

Upvotes: 9

Related Questions