asp.net-mvc 我们如何声明局部变量并输出其值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11019351/
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
How can we declare local variable and output its value?
提问by Idrees Khan
I have declared a variable like this
我已经声明了一个这样的变量
@{ int i = 1; }
Now, inside foreachloop i want to assign the value of i each time the loop is processed;
现在,在foreach循环内部,我想在每次处理循环时分配 i 的值;
@foreach (var line in Model.Cart.Lines)
{
<input type="hidden" name="item_name_@i" value="@line.Product.ProductName" />
<input type="hidden" name="amount_@i" value="@line.Product.Price" />
<input type="hidden" name="quantity_@i" value="@line.Quantity" />
@i++;
}
but it isn't working.
但它不起作用。
Any solution?
有什么解决办法吗?
采纳答案by Kirk Woll
If you need access to the index, it makes more sense to use a normal forloop:
如果您需要访问索引,使用普通for循环更有意义:
@for (int i = 0; i < Model.Cart.Lines.Count; i++)
{
var line = Model.Cart.Lines[i];
...
}
Alternatively, you could use a LINQ expression:
或者,您可以使用 LINQ 表达式:
@foreach (var item in Model.Cart.Lines.Select((x, i) => new { Line = x, Index = i }))
{
// Now you can access, for example, `item.Line` for the line, and
// `item.Index` for the index (i.e. `i`)
...
}
回答by yoel halb
You haven't explained what isn't working, but from your code it appears that the value of the "i" variable isn't incrementing, instead you vet an output of "0++;".
您还没有解释什么不起作用,但是从您的代码看来,“i”变量的值没有增加,而是您检查了“0++;”的输出。
This is because the purpose of the @ symbol in razor is
这是因为 razor 中 @ 符号的目的是
- to output
- identifiers, and therefore it outputs the identifier "i" and then continues with the remaining text of "++;".
- 输出
- 标识符,因此它输出标识符“i”,然后继续“++;”的剩余文本。
To achieve what you apparently want to do (to just increment the value of i), you have to enclose it in a code block, as follows:
为了实现您显然想要做的事情(只是增加 i 的值),您必须将其包含在代码块中,如下所示:
@{ i++; }
However if you do want to output the value of i before incrementing it, then you should wrap it in a expression block, as in the following:
但是,如果您确实想在增加 i 之前输出它的值,那么您应该将它包装在一个表达式块中,如下所示:
@(i++)
回答by user2684726
I'm thinking scope. see http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvc3razor.aspx
我在考虑范围。请参阅http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvc3razor.aspx
try it one code block like:
尝试一个代码块,如:
@{
var i = 1;
var tmp = "";
foreach (var line in Model.Cart.Lines)
{
tmp = "item_name_" + i;
<input type="hidden" name="@tmp" value="@line.Product.ProductName" />
i++;
}
}

