KeizerHarm
KeizerHarm

Reputation: 330

Razor - How to store html special character in variable

On my html page, I want to make a list from a collection of entries in my model. However, some of those entries may be null, and in that case I want to have an empty list item, like so:

I do that by inserting a non-breaking space character. (regular whitespace won't generate empty list items) Here's a code snippet:

<ul>
    @{ 
        foreach (var x in Model.Entries)
        {
            var rayon = x.Rayon ?? "&nbsp;";
            <li>@rayon</li>
        } 
    }
</ul>

Sadly, this does not work because it instead pastes &nbsp; verbatim. And removing the quotation marks, and/or adding @: at the start, won't compile.

What can I do?

Upvotes: 0

Views: 1042

Answers (2)

AdaTheDev
AdaTheDev

Reputation: 147234

Instead of "&nbsp;" just give a blank string:

var rayon = x.Rayon ?? string.Empty;

In fact, I think you can even just scrap that variable assignment together and just use x.Rayon as-is - a null value should have the same effect

<ul>
    @{ 
        foreach (var x in Model.Entries)
        {     
            <li>x.Rayon</li>
        } 
    }
</ul>

Update: Both above work for me. So, if still not working, it looks to be down to CSS/styles on your ul.

e.g. OK, I think this is down to CSS/styles on the ul that you have then (both above work fine for me). e.g. the following CSS would hide empty li elements:

ul li:empty {
   display: none;
}

So, check out your CSS.

If you don't want to change the existing style, you could add an extra class to your CSS and apply that for just this instance. i.e. CSS:

ul.show-empty-li li:empty{
    display:list-item;
}

HTML:

<ul class="show-empty-li">
...
</ul>

Upvotes: 1

Amit Kumar
Amit Kumar

Reputation: 5962

You can use Html.Raw.

use like this

<li> @(Html.Raw(rayon)) </li>

Upvotes: 2

Related Questions