剃刀视图中的三元运算符将代码返回为字符串

时间:2015-03-19 10:45:47

标签: asp.net-mvc razor

我想格式化数据,但结果错误,我该如何解决?

 <div>
        @string.IsNullOrEmpty(Model.Customer.State) ? @Model.Customer.Country : @string.Format("{0}, {1}", Model.Customer.Country, Model.Customer.State);
    </div>

它返回:

True ? French: French, ;

2 个答案:

答案 0 :(得分:1)

您只需添加一些括号,以便将其视为一个语句块...

<div>
    @(string.IsNullOrEmpty(Model.Customer.State) ? Model.Customer.Country : string.Format("{0}, {1}", Model.Customer.Country, Model.Customer.State));
</div>

答案 1 :(得分:1)

你必须用括号括起整个条件:

<div>
    @(string.IsNullOrEmpty(Model.Customer.State) ? Model.Customer.Country : string.Format("{0}, {1}", Model.Customer.Country, Model.Customer.State))
</div>