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?
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With