【问题标题】:.NET razor show custom text if model is null如果模型为空,.NET 剃须刀显示自定义文本
【发布时间】:2022-01-14 15:47:17
【问题描述】:

假设我有以下模型:

public class Parent : BaseEntity
{
    public Child? Child { get; set; }
}

public class Child: BaseEntity
{
    public string? Name { get; set; }
}

然后我将父模型发送到我的视图:

@model Parent

如果孩子为空,我想显示一个自定义的孩子名。我怎样才能在类似于以下的 1 行中做到这一点?

<input type="text" placeholder="@Model.Child?.Name ?? DefaultName">

【问题讨论】:

  • "@Model.Child?.Name ?? DefaultName"(顺便说一句,你不需要string?string 很好,Child? 也一样,因为它是一个引用类型。)
  • 我想我错过了一些东西。它不工作。 :/ Btw with .NET6 string 变成了一个可为空的类型。

标签: c# html asp.net razor razor-pages


【解决方案1】:

我在这里找到了解决方案:

How to get the Null Coalesce operator to work in ASP.NET MVC Razor?

语句应该被包裹在 () 之间,如下所示:

<input type="text" placeholder=@(Model.Child?.Name ?? "DefaultName")>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-05
    • 2015-08-01
    • 2019-10-27
    • 1970-01-01
    • 2023-03-17
    • 2022-10-16
    • 2021-03-01
    • 1970-01-01
    相关资源
    最近更新 更多