【问题标题】:ASP.NET MVC Razor: TernaryASP.NET MVC 剃刀:三元
【发布时间】:2011-12-05 10:53:50
【问题描述】:

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

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

我该怎么做?

更新:抱歉,问题略有改变。

【问题讨论】:

  • 你可以使用空合并操作符吗?类似于:@Model.MyString ?? “‘空’”
  • 我同意@Darin Dimitrov。 三元、循环、C# 和其他东西让视图变得丑陋。

标签: asp.net view razor


【解决方案1】:

三元、循环、C# 和其他东西让视图变得丑陋。

这正是视图模型的设计目的:

public class MyViewModel
{
    [DisplayFormat(NullDisplayText = "null", DataFormatString = "'{0}'"]
    public string MyProperty { get; set; }
}

然后在你的强类型视图中简单地:

@model MyViewModel
...
@Html.DisplayFor(x => x.MyProperty)

【讨论】:

    【解决方案2】:

    假设您有一个名为 Test 且具有 FirstLast 属性的实体:

    public class Test {
    
        public string First { get; set; }
    
        public string Last { get; set; }
    }
    

    你可以使用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; }
    }
    

    在视图中:

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

    我也改了答案:

    [DisplayFormat(DataFormatString = "'{0}'", NullDisplayText = "null")]
    

    【讨论】:

      【解决方案3】:

      你应该可以像标题所暗示的那样使用三元运算符:

      @(string.IsNullOrEmpty(Model.Prop) ? "null" : "'" + Model.Prop + "'")
      

      【讨论】:

      • 完美!我使用的是“{}”而不是“()”!
      猜你喜欢
      • 2011-04-12
      • 2011-06-09
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      相关资源
      最近更新 更多