views:

1900

answers:

3

In my asp.net-mvc website I have a field that usually has a string (from database) but can from time to time contain nothing. Because IE doesn't know how to handle the css "empty-cells" tag, empty table cells need to be filled with an  
I thought

Html.Encode(" ");

would fix this for me, but apparantly, it just returns " ". I could implement this logic as follows

Html.Encode(theString).Equals(" ")?" ":Html.Encode(theString);

Also a non-shorthand-if would be possible but frankly, both options are but ugly. Isn't there a more readable, compact way of putting that optional space there?

A: 

You have to find a different way to fill your empty cell. HTML-encoding a space character to itself is perfectly valid. If you need it to be something else you could use URL escaping or roll your own method to generate the content.

Bombe
+2  A: 

A space encode in HTML is just a space. nbsp may look like a space, but has a different semantics, "non-breaking" meaning that line breaks are suppressed.

Solution: Whenever I find functionality lacking or with unexpected behavior (e.g. asp:Label and HyperLink don't HTML encode), I write my own utilities class which does as I say ;)

public class MyHtml
{
    public static string Encode(string s)
    {
        if (string.IsNullOrEmpty(s) || s.Trim()=="")
            return "& nbsp;";
        return Html.Encode(s);
    }
}
devio
Yes, I was planning something like this. But before I start implementing my own (and introduce possible change dependancies/bugs) I wanted to be sure there is no better solution.
borisCallens
I think you should have a special case, like MyHtml.TdEncode which does this. You don't want to add nbsps everyhwere. Also, what is the difference between isNullOrEmpty(s) and s.Trim() == ""? Seems like the trim call is superfluous
Juan Mendes
+1  A: 

It might be simpler to convert the " " to "\xA0" and then unconditionally Html.Encode the result:

s = (string.IsNullOrEmpty(s) || s.Trim()=="") ? "\xA0" : s;
Html.Encode(s);

Hexadecimal 00A0 identifies the Unicode character for non-breaking space, which is why   is an equivalent HTML entity to  .

If you have any control over the database, you could convert the empty or single-space fields to this "\xA0" value, which would eliminate the condition altogether.

system PAUSE
Thank you for the pointer to `\xA0`! That came in handy today for something similar to this.
Cymen