简体   繁体   English

C#代码块中的Razor语法

[英]Razor syntax in c# code block

Trying to populate table data with: 尝试使用以下方法填充表数据:

        @foreach (var mc in Model.McList)
        {
            <tr>
                <td>
                    @(@mc.Amount != null ? @mc.Amount @@ @mc.Price : null)
                </td>
            </tr>
        }

but stuck in razor syntax errors: 但陷入剃刀语法错误:

expect : 期望:

expect ) 期待)

or ambiguous invocation: void Write 或模棱两可的调用:无效写入

Amount is int? 金额是整数? nullable type. 可为null的类型。

@(@mc.Amount != null ? @mc.Amount : null) //works only with one property
@if (@mc.Amount != null) {@mc.Amount <text>@@</text> @mc.Price} //works
@if (@mc.Amount != null) {@mc.Amount @@ @mc.Price} //error
@if (@mc.Amount != null) {@mc.Amount @:@@ @mc.Price} //error

is it shorter way to check for null value without if? 是没有if的更短方法来检查null值吗?

I don't think that's possible. 我认为那是不可能的。 If you must do that in one line, the closest I get is: 如果必须在一行中执行此操作,则我得到的最接近的结果是:

@(@mc.Amount != null ? string.Format("{0} @ {1}", mc.Amount, mc.Price) : null)

I'd probably never do that myself! 我可能永远不会自己做!

I think you're trying to make something that looks like this: 我认为您正在尝试制作如下所示的内容:

5 @ 20 5 @ 20

If so, you need to keep in mind that everything between @( and ) is pure C# code; 如果是这样,您需要记住@()之间的所有内容都是纯C#代码; what you need to do is something like this: 您需要做的是这样的:

@(mc.Amount != null ? string.Format("{0} @ {1}", mc.Amount, mc.Price) : "")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM