[英]asp.net mvc razor foreach loop adding id to div
I am trying to add dynamic id
to div
inside a foreach
loop concatenated with value of variable i
. 我试图在与变量i
值连接的foreach
循环内向div
添加动态id
。 It throws syntax errors. 它会引发语法错误。 What might be the issue. 可能是什么问题。 Can we achieve this solution without using a for
loop ? 我们能不使用for
循环来实现这个解决方案吗?
@{int i=1;}
@foreach (var or in Model.Names)
{
<div oid="@or.Id" mode="0" oids="@or.Id" id="tr"+i>
@or.Name
</div>
i++;
}
You want to construct ID in C# segment of code. 您想在C#代码段中构造ID。 One option is to do whole construction with string format: 一种选择是使用字符串格式进行整个构造:
<div oid="@or.Id" mode="0" oids="@or.Id" id="@string.Format("tr{0}",i)">
Or id="@("tr"+i)"
or id="tr@(i)"
或id="@("tr"+i)"
或id="tr@(i)"
Note that you can't do just id="tr@i"
because the Razor syntax parser ignores "text@text" as it looks like a normal email address. 请注意,您不能只执行id="tr@i"
因为Razor语法分析器会忽略“text @ text”,因为它看起来像普通的电子邮件地址。
You can't append like this: 你不能这样追加:
id="tr"+i>
It must be: 一定是:
id="tr@i">
You need the @
.. since it won't be able to deduce between markup and Razor at that point. 你需要@
..因为在那时它无法在标记和Razor之间推断。
在新的C#6中你可以直接使用id =“@($”tr {i}“)”
for myself, none of this solutions worked but adding my @i first did work, id="@i+AnyText"
after building it, and inspecting ill get id="1+AnyText"
, for the next one id="2+AnyText"
and so on (im using 2013vs).. 对我自己来说,这些解决方案都没有起作用,但是在构建它之后添加我的@i首先做了工作, id="@i+AnyText"
,并且检查了ill get id="1+AnyText"
,对于下一个id="2+AnyText"
依此类推(即时使用2013vs)..
hope that helps anyone, have a nice day. 希望能帮到任何人,祝你有个美好的一天。
经过一段时间的努力,我发现id="@("tr"+i)"
为我做了这份工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.