Is there a way to get an @Html.DisplayFor
value to show "NULL" in the view if the value of the model item is null
?
Here's an example of an item in my Details view that I'm working on currently. Right now if displays nothing if the value of the Description is null
.
<div class="display-field">
@Html.DisplayFor(model => model.Description)
</div>
是的,我会建议使用以下数据标注与您codefirst模型可为空的日期时间字段:
[Display(Name = "Last connection")]
[DisplayFormat(NullDisplayText = "Never connected")]
public DateTime? last_connection { get; set; }
那么在你看来:
@Html.DisplayFor(x => x.last_connection)
显示一个字符串,例如“ - ”代替空值的通过“DisplayFor”标准的辅助显示使用辅助,例如:“DisplayForNull”
1.创建文件夹“助手”,并添加新的控制器“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.在您的视图
@using WIPRO.Helpers
@Html.DisplayForNull(model => model.CompanyOwnerPersonName)
代替
@Html.DisplayFor(model => model.CompanyOwnerPersonName)
希望能帮助到你 ;-)