ASP.NET MVC Razor:三元

use*_*672 2 asp.net view razor

使用带有Razor视图引擎的三元组时遇到一些麻烦.

我的模型有一个字符串属性.如果该字符串属性为null,我想null在视图中呈现.如果属性不为null,我希望它使用前导和尾随呈现属性值'.

我怎样才能做到这一点?

更新:对不起,稍微改了一下问题.

Sea*_*ter 11

您应该只能使用标题建议的三元运算符:

@(string.IsNullOrEmpty(Model.Prop) ? "null" : "'" + Model.Prop + "'")
Run Code Online (Sandbox Code Playgroud)

  • 完善!我使用'{}'而不是'()'! (3认同)

jav*_*iry 7

假设你有一个名为实体TestFirstLast特性:

public class Test {

    public string First { get; set; }

    public string Last { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用DisplayFormat.DataFormatStringDisplayFormat.NullDisplayText实现您的目的:

public class Test {

    [Display(Name = "First Name")]
    [DisplayFormat(DataFormatString = "'{0}'", NullDisplayText = "'null'")]
    public string First { get; set; }

    [Display(Name = "Last Name")]
    [DisplayFormat(DataFormatString = "'{0}'", NullDisplayText = "'null'")]
    public string Last { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在视图中:

@Html.DisplayFor(model => model.First)

@Html.DisplayFor(model => model.Last)
Run Code Online (Sandbox Code Playgroud)

我也改变了答案:

[DisplayFormat(DataFormatString = "'{0}'", NullDisplayText = "null")]
Run Code Online (Sandbox Code Playgroud)