asp.net-mvc html 元素属性内的 Razor 语法(ASP MVC 3)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3696071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Razor syntax inside attributes of html elements (ASP MVC 3)
提问by Martin
I have a table with repeating customer rows, I would like to add the customer ID to the ID attribute of my table rows like this:
我有一个包含重复客户行的表,我想将客户 ID 添加到我的表行的 ID 属性中,如下所示:
<tr id="row<customer id>"></tr>
I try adding this code:
我尝试添加此代码:
@foreach(var c in Model) {
<tr id="[email protected]"></tr>
}
Which gives me the following output:
这给了我以下输出:
<tr id="[email protected]"></tr>
<tr id="[email protected]"></tr>
etc.
等等。
But I would like it to be:
但我希望它是:
<tr id="row1"></tr>
<tr id="row2"></tr>
etc.
等等。
I also tried to add <tr>row@{c.id}</tr>
but it did not work..
我也尝试添加<tr>row@{c.id}</tr>
但它不起作用..
回答by Buildstarted
have you tried <tr>row@(c.id)</tr>
?
你试过<tr>row@(c.id)</tr>
吗?
The actual reason why this doesn't work is because your [email protected]
matches the regexfor an email address. So the parser assumes it's an email and not actually an attempt to call code. The reason row@{c.id}
doesn't work is because the @{}
doesn't output and is meant to contain blocks of code.
这不起作用的实际原因是因为您[email protected]
匹配了电子邮件地址的正则表达式。所以解析器假定它是一封电子邮件,而不是实际上试图调用代码。原因row@{c.id}
不起作用是因为@{}
不输出并且旨在包含代码块。
When in doubt you should use @()
as it will force what's contained between the ()
to be parsed as code.
如有疑问,您应该使用,@()
因为它会强制将 之间包含的内容()
解析为代码。