1

I am working on asp.net MVC 5, I created a helper for boolean.

I wrote this:

public class CustomHelper
    {
        public static string Boolean(bool? value)
        {
            if(value == true )
                return string.Format("<span class='glyphicon glyphicon-ok green'></span>");
            else
                return string.Format("<span class='glyphicon glyphicon-remove red'></span>");
        }
    }

and the Razor is:

<td>
     @CustomHelper.Boolean(item.Deleted)
</td>

but the result is the same as the photo. the html appears as a string enter image description here

how to fix it? so I can show the symbol instead? thank you

4
  • please a little explination, I did not understand what do you mean Commented Oct 16, 2016 at 12:34
  • Use MvcHtmlString.Create instead of string.format Commented Oct 16, 2016 at 12:35
  • And your helper is not an extension to MVC helpers it's just a class that has a method. Check mvc helpers concept in asp.net site Commented Oct 16, 2016 at 12:37
  • it works, thank you Commented Oct 16, 2016 at 13:14

1 Answer 1

1

By default, the @ symbol encodes the output. You should create your custom check as an extension method to the HtmlHelper class as below

    public static class BooleanExtensions
         {
              public static MvcHtmlString Boolean(this HtmlHelper helper, bool value)
              {
                  var spanTag = new TagBuilder("span");
                  if(value)
                     spanTag.MergeAttribute("class", glyphicon glyphicon-ok green");
                  else
                     spanTag.MergeAttribute("class", glyphicon glyphicon-remove red");

                   return MvcHtmlString.Create(spanTag.ToString(TagRenderMode.EndTag));           

              }
         }

Next, in your Razor view, call it as:

@Html.Boolean(item.Deleted)

Don't forget to add the @using for the namespace that has the class in the beginning of the view

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.