有没有办法让@Html.DisplayFor
值显示" NULL"在视图中,如果模型项的值是null
?
这是我目前正在处理的详细信息视图中的项目示例。现在,如果描述的值为null
,则不显示任何内容。
<div class="display-field">
@Html.DisplayFor(model => model.Description)
</div>
答案 0 :(得分:61)
是的,我建议在codefirst模型中使用以下数据注释和可空的datetime字段:
[Display(Name = "Last connection")]
[DisplayFormat(NullDisplayText = "Never connected")]
public DateTime? last_connection { get; set; }
然后在你看来:
@Html.DisplayFor(x => x.last_connection)
答案 1 :(得分:0)
Display a string e.g. "-" in place of null values show via the "DisplayFor" standard helper using a helper extension, i.e. "DisplayForNull"
1. Create Folder "Helpers" and add a new controller "Helper.cs"
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
namespace WIPRO.Helpers
{
public static class Helpers
{
public static MvcHtmlString DisplayForNull<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string valuetodisplay = string.Empty;
if (metaData.Model != null)
{
if (metaData.DisplayFormatString != null)
{
valuetodisplay = string.Format(metaData.DisplayFormatString, metaData.Model);
}
else
{
valuetodisplay = metaData.Model.ToString();
}
}
else
{
valuetodisplay = "-";
}
return MvcHtmlString.Create(valuetodisplay);
}
}
2. In your view
@using WIPRO.Helpers
@Html.DisplayForNull(model => model.CompanyOwnerPersonName)
in place of
@Html.DisplayFor(model => model.CompanyOwnerPersonName)
Hope it helps ;-)