asp.net-mvc - 检查 DateTime 类型的值是否在 View 中为空,如果为空则显示空白

标签 asp.net-mvc asp.net-mvc-4 view nullable

从我的 Controller 中,我已将值模块传递给查看

    public ActionResult Details(long id, string owner)
    {
        var module = _ownedModuleRepository.GetModuleDetails(id, owner);

        return View(module);
    }

我在 View 中显示了它包含的值,如下所示
    <dt>ID</dt>
    <dd>@Model.Id</dd>

    <dt>Module ID</dt>
    <dd>@Model.ModuleId</dd>

     <dt>Owner</dt>
    <dd>@Model.Owner</dd>

    <dt>Module Type</dt>
    <dd>@Model.TypeName</dd>

    <dt>Module Kind</dt>
    <dd>@Model.KindName</dd>

    <dt>Ownership Start Date</dt>
    <dd>@Model.Start</dd>

    <dt>Ownership End Date</dt>
    <dd>@Model.End</dd>

    @foreach (var properties in Model.Properties)
    {
        <dt>Property Name</dt>
        <dd>@properties.Name</dd>
        <dt>Property Value</dt>
        <dd>@properties.Value</dd>
    }

目前 @Model.End 为空,它是 DateTime 类型,我在 viewmodel 中将它设置为可为空。
因为它是空的,这就是我所看到的

enter image description here

如您所见,Ownership End Date 的值取自下方的 Property Name 的值。如果@Model.End 为空,如何将其设置为空?

编辑 1:

我的模型
public class OwnedModuleDetails
{
    public long Id { get; set; }

    public string ModuleId { get; set; }

    public string Owner { get; set; }

    public string KindName { get; set; }
    public string TypeName { get; set; }

    public DateTime Start { get; set; }

    public DateTime? End { get; set; }

    public IEnumerable<Property> Properties { get; set; }
}

来自存储库的方法
     public OwnedModuleDetails GetModuleDetails(long id, string owner)
        {
// ReSharper disable ImplicitlyCapturedClosure
            var module = (_dbSis.OwnedModules.Where(t => t.Id == id).Select(m => new OwnedModuleDetails
// ReSharper restore ImplicitlyCapturedClosure
            {
                Id = id,
                ModuleId = m.ModuleId,
                TypeName = m.ModuleType.TypeName,
                KindName = m.ModuleType.ModuleKind.KindName,
                Owner = owner,
                Start = m.Start,
                End = m.End,
                Properties = m.PropertyConfiguration.PropertyInstances.Select(
                    x => new Property { Name = x.Property.Name, Value = x.Value })
            }));

            return (module.FirstOrDefault());
        }

最佳答案

当用户在日期列中插入空值时,我曾经遇到过这个问题。
导致此错误:System.InvalidOperationException: Nullable object must have a value为了解决这个问题而不是 DisplayFor只需在您的 View 中使用下面的代码,因此如果列值为 null,它将显示 Date is Empty

 <td>
            
@(item.Startdate.HasValue ? item.Startdate.Value.ToString("dd/MM/yyyy") : "Date is Empty")

</td>
进一步阅读 thisthis用于模型
希望能帮助某人。

关于asp.net-mvc - 检查 DateTime 类型的值是否在 View 中为空,如果为空则显示空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17918793/

相关文章:

Cocoa 加载 ViewNib

SQLite:当整行不唯一时删除重复行

c# - 使用当前用户 ID 初始化 ASP.NET MVC Controller

c# - MVC4 使用什么加密?

c# - 生成小型 HTML 片段的辅助方法

c# - 在表格的列标题处插入间距

android - View.isActivated() 是做什么的?

c# - 管理匿名用户的 SignalR 连接

c# - MVC 从单个 View 创建多个对象

c# - Site.Master 中的一些东西可以有条件地显示(MVC)吗?