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

能够执行以下操作似乎相当简单:

@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>
}

但这行不通。这可能吗?


当前回答

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

@{
    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>
    }
}

其他回答

我觉得你已经很接近了,试试这个:

@{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>
}

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

@{
    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>
    }
}

你可以把所有东西都放在一个块中,并轻松地在该块中编写任何你想要的代码,只是下面的代码:

@{
        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>
        }
    }

它可以帮助你有一个更干净的代码,也可以防止你的页面加载多次不同的代码块

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

@{
  int counter = 1;

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

你还可以使用:

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

代码中不需要变量