Html.Encode () does not encode space

In my asp.net-mvc website, I have a field that usually has a string (from the database), but may not contain anything at times. Since IE doesn't know how to handle the "empty-cells" css tag, empty table cells must be filled with & nbsp.
I thought that

Html.Encode(" ");

      

will fix this for me, but it will just return "". I could implement this logic like this

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

Also, not a transcript - if possible, but frankly, both are ugly. Isn't there a more readable and compact way to accommodate that extra space?

+1


source to share


3 answers


Space encoding in HTML is just a space. nbsp may look like a space, but it has a different semantics, "non-breaking", which means that line breaks are suppressed.

Solution: whenever I find functionality devoid of or unexpected behavior (like asp: Label and HyperLink do not HTML encode), I write my own utility class that 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);
    }
}

      

+2


source


It might be easier to convert " "

to "\xA0"

, and then unconditionally the Html.Encode

result:

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

      



Hexadecimal 00A0

defines the Unicode character for the non-breaking space, therefore it  

is the equivalent HTML object  

.

If you have any control over the database, you can convert empty or one-space to this value "\xA0"

, which will eliminate the condition entirely.

+5


source


You need to find another way to fill in a blank cell. HTML encoding the space character is perfectly fair for yourself. If you need this to be something else, you could use URL escaping or translate your own method for creating content.

0


source







All Articles