Show “NULL” for null values in ASP.NET MVC DisplayFor Html Helper

倾然丶 夕夏残阳落幕 提交于 2019-12-09 07:48:37

问题


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>

回答1:


yes, I would recommend using the following data annotation with a nullable datetime field in your codefirst model :

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

then in your view :

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



回答2:


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 ;-)



来源:https://stackoverflow.com/questions/15981594/show-null-for-null-values-in-asp-net-mvc-displayfor-html-helper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!