I have a need to insert a
via @HTML.DisplayFor
when the backing model's value is null or empty.
I've tried using data annotations
[DisplayFormat(ConvertEmptyStringToNull = true, NullDisplayText =" " ]
public string MiddleName { get; set; }
which does work to stick a " " where I expect it but I need to put a non-breaking space there instead.
A commonly used entity in HTML is the non-breaking space: A non-breaking space is a space that will not break into a new line. Two words separated by a non-breaking space will stick together (not break into a new line). This is handy when breaking the words might be disruptive.
In CSS property padding and margin can be used to tab space instead of non-breaking spaces (nbsp).
DisplayFor<TModel,TValue>(HtmlHelper<TModel>, Expression<Func<TModel,TValue>>, String, String, Object) Returns HTML markup for each property in the object that is represented by the specified expression, using the template, an HTML field ID, and additional view data.
HtmlEncode is only meant to encode characters for display in HTML. It specifically does not encode whitespace characters. I would go with your first option, and make it an extension method for HtmlHelper.
This works for me:
NullDisplayText = @" ", HtmlEncode = false
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