我正在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 so continue
    <div>
        <div> click to join us </div>
        <a id="login" href="javascript:void(0);" style="display: inline; ">join here</a>
    </div>
}

其他回答

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

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

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

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

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

如果您希望一个变量在整个页面中都可以访问,最好在文件的顶部定义它。(可以使用隐式类型也可以使用显式类型。)

@{
    // implicit type
    var something1 = "something";

    // explicit type
    string something2 = "something";
}

<div>@something1</div> @*display first variable*@
<div>@something2</div> @*display second variable*@