Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html literal in Razor ternary expression

I'm trying to do something like the following

<div id="test">     @(         string.IsNullOrEmpty(myString)           ? @:&nbsp;           : myString        ) </div> 

The above syntax is invalid, I've tried a bunch of different things but can't get it working.

like image 981
fearofawhackplanet Avatar asked Jul 28 '11 10:07

fearofawhackplanet


1 Answers

Try the following:

@Html.Raw(string.IsNullOrEmpty(myString) ? "&nbsp;" : Html.Encode(myString)) 

But I would recommend you writing a helper that does this job so that you don't have to turn your views into spaghetti:

public static class HtmlExtensions {     public static IHtmlString ValueOrSpace(this HtmlHelper html, string value)     {         if (string.IsNullOrEmpty(value))         {             return new HtmlString("&nbsp;");         }         return new HtmlString(html.Encode(value));     } } 

and then in your view simply:

@Html.ValueOrSpace(myString) 
like image 119
Darin Dimitrov Avatar answered Oct 12 '22 16:10

Darin Dimitrov