Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a non-breaking space in a @Html.DisplayFor when data is null or empty? ASP.Net MVC

Tags:

c#

asp.net-mvc

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.

like image 720
John S Avatar asked Feb 18 '14 18:02

John S


People also ask

What is non-breaking space in HTML?

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.

What can I use instead of &Nbsp?

In CSS property padding and margin can be used to tab space instead of non-breaking spaces (nbsp).

What does HTML DisplayFor do?

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.

What is HTML encoding in MVC?

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.


1 Answers

This works for me:

NullDisplayText = @"&nbsp;", HtmlEncode = false
like image 114
Angel Oterino Avatar answered Oct 05 '22 20:10

Angel Oterino