简体   繁体   English

字符串中的C#Razor语法

[英]C# Razor Syntax inside a string

This is the Code I'm having problems with: 这是我遇到问题的代码:

@{int i = 1;}
@foreach (var item in Model)
{
    @:<ul id="sortablei" class='droptrue'>
    i++;
}

How can I use i in the id sortablei? 如何在id sortablei中使用i? I tried: @i or @{i} but it seems without a space before the i its not working. 我试过了:@ i或@ {i}但似乎没有空格之前我没有工作。 I couldn't find an answer to my problem in the Razor Syntax Reference so I'm a bit clueless right now. 我在Razor语法参考中找不到我的问题的答案,所以我现在有点无能为力。

Brackets: 括号:

@:<ul id="sortable@(i)" class='droptrue'>

The brackets here scope the razor expression; 这里的括号是剃刀表达的范围; in many cases they aren't required, however they are necessary when: 在许多情况下,它们不是必需的,但在以下情况下它们是必需的

  • the expression (on the right) is non-trivial (spaces. etc) and needs help to scope it 表达式(在右边)是非平凡的(空格等)并且需要帮助来限定它
  • where without it, it looks like an email address, ie abc@def - this has special handling to avoid breaking pages with email addresses in them 没有它,它看起来像一个电子邮件地址,即abc@def - 这有特殊处理,以避免打破其中包含电子邮件地址的页面

something like this: 这样的事情:

@model System.Generic.Collections.List<MyNameSpace.Product>
@{
    int i = 1;
    string sortablei = "abc",
           droptrue = "abc-cls";
}

<ul id="@sortablei" class="@droptrue">
    @foreach (var item in Model)
    {
       <li>@item.Qty x @item.Name</li>
       i++;
    }
</ul>

Here's a quick reference for your knowledge. 这是您的知识的快速参考


Seams like I didn't got it right, 像我这样的接缝没有把它弄好,

as Mark said, all you need to do is surround the variable with brackets like 正如马克所说,你需要做的就是用括号括起变量

sortable@(i)

I hope the reference is somewhat useful, as your particular problem can be found in Explicit Expression example 我希望该引用有点用处,因为您可以在Explicit Expression示例中找到您的特定问题

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

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