如何在Razor中声明局部变量?

问题描述 投票:320回答:6

我正在asp.net mvc 3中开发一个Web应用程序。我对它很新。在使用剃刀的视图中,我想声明一些局部变量并在整个页面中使用它。如何才能做到这一点?

能够执行以下操作似乎相当微不足道:

@bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);
@if (isUserConnected)
{ // meaning that the viewing user has not been saved
    <div>
        <div> click to join us </div>
        <a id="login" href="javascript:void(0);" style="display: inline; ">join</a>
    </div>
}

但这不起作用。这可能吗?

c# .net asp.net-mvc asp.net-mvc-3 razor
6个回答
479
投票

我觉得你很亲密,试试这个:

@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);}
@if (isUserConnected)
{ // meaning that the viewing user has not been saved so continue
    <div>
        <div> click to join us </div>
        <a id="login" href="javascript:void(0);" style="display: inline; ">join here</a>
    </div>
}

47
投票

我认为变量应该在同一个块中:

@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);
    if (isUserConnected)
    { // meaning that the viewing user has not been saved
        <div>
            <div> click to join us </div>
            <a id="login" href="javascript:void(0);" style="display: inline; ">join</a>
        </div>
    }
    }

18
投票

您还可以使用:

@if(string.IsNullOrEmpty(Model.CreatorFullName))
{
...your code...
}

代码中不需要变量


11
投票

如果你正在寻找一个int变量,一个随着代码循环而递增的变量,你可以使用这样的东西:

@{
  int counter = 1;

  foreach (var item in Model.Stuff) {
    ... some code ...
    counter = counter + 1;
  }
} 

7
投票

不是OP问题的直接答案,但它也可能对你有所帮助。您可以在范围内的某个html旁边声明一个局部变量而不会出现问题。

@foreach (var item in Model.Stuff)
{
    var file = item.MoreStuff.FirstOrDefault();

    <li><a href="@item.Source">@file.Name</a></li>
}

1
投票

声明要在整个页面中访问的var ....页面顶部通常可以解决。隐含或明确的选择。

          @{
               //implicit
               var something1 = "something";
               //explicit
               string something2 = "something";
          }


            @something1 //to display on the page
            @something2 //to display on the page
© www.soinside.com 2019 - 2024. All rights reserved.