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.
Try something like:
var space = " ";
[DisplayFormat(ConvertEmptyStringToNull = true, NullDisplayText ="@space" ]
public string MiddleName { get; set; }
The issue with placing " "
in that location is that it will be read as c# code. Instead, you want it to be read as HTML code at run time, and the above should achieve this.
这对我有用:
NullDisplayText = @" ", HtmlEncode = false
I worked around this problem by writing a helper instead of using @Html.DisplayFor
. This is it.
@helper NonBreakingSpacesIfNullOrEmpty(string field, int spaces)
{
if (String.IsNullOrEmpty(field))
{
@(new HtmlString(String.Concat(Enumerable.Repeat(" ", spaces))))
}
else
{
@field
}
}
Your code would call it like this.
@FooHelper.NonBreakingSpacesIfNullOrEmpty(Model.MiddleName, 1)
Delete the spaces
parameter and the associated logic if you don't need the repeat functionality.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.