我正在asp.net mvc 3中開發一個Web應用程序。我對它很新。 在使用剃刀的視圖中,我想聲明一些局部變量并在整個頁面中使用它。 如何才能做到這一點?
能夠執行以下操作似乎相當微不足道:
@bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);
@if (isUserConnected)
{ // meaning that the viewing user has not been saved
join
}
但這不起作用。 這可能嗎?
#1樓
您還可以使用:
@if(string.IsNullOrEmpty(Model.CreatorFullName))
{
...your code...
}
代碼中不需要變量
#2樓
如果你正在尋找一個int變量,一個隨著代碼循環而遞增的變量,你可以使用這樣的東西:
@{
int counter = 1;
foreach (var item in Model.Stuff) {
... some code ...
counter = counter + 1;
}
}
#3樓
不是OP問題的直接答案,但它也可能對你有所幫助。 您可以在范圍內的某個html旁邊聲明一個局部變量而不會出現問題。
@foreach (var item in Model.Stuff)
{
var file = item.MoreStuff.FirstOrDefault();
@file.Name}
#4樓
聲明要在整個頁面中訪問的var ....頁面頂部通常可以解決。 隱含或明確的選擇。
@{
//implicit
var something1 = "something";
//explicit
string something2 = "something";
}
@something1 //to display on the page
@something2 //to display on the page
#5樓
我覺得你很親密,試試這個:
@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);}
@if (isUserConnected)
{ // meaning that the viewing user has not been saved so continue
join here
}