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)
假设你有一个名为实体Test
与First
和Last
特性:
public class Test {
public string First { get; set; }
public string Last { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
您可以使用DisplayFormat.DataFormatString
并DisplayFormat.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)
归档时间: |
|
查看次数: |
2404 次 |
最近记录: |