显示“NULL”在ASP.NET MVC DisplayFor HTML帮助空值(Show “NUL

2019-08-22 14:07发布

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>

Answer 1:

是的,我会建议使用以下数据标注与您codefirst模型可为空的日期时间字段:

[Display(Name = "Last connection")]
[DisplayFormat(NullDisplayText = "Never connected")]
public DateTime? last_connection { get; set; }

那么在你看来:

@Html.DisplayFor(x => x.last_connection)


Answer 2:

显示一个字符串,例如“ - ”代替空值的通过“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)

希望能帮助到你 ;-)



文章来源: Show “NULL” for null values in ASP.NET MVC DisplayFor Html Helper