How to declare a local variable in Razor?

401,822

Solution 1

I think you were pretty close, try this:

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

Solution 2

I think the variable should be in the same block:

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

Solution 3

You can also use:

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

No need for a variable in the code

Solution 4

Not a direct answer to OP's problem, but it may help you too. You can declare a local variable next to some html inside a scope without trouble.

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

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

Solution 5

If you're looking for a int variable, one that increments as the code loops, you can use something like this:

@{
  int counter = 1;

  foreach (var item in Model.Stuff) {
    ... some code ...
    counter = counter + 1;
  }
} 
Share:
401,822
vondip
Author by

vondip

I am a an entrepreneur and developer. Working on my startup - A simple photoshop for non professionals. You can check it out on: http://bazaart.me

Updated on December 24, 2020

Comments

  • vondip
    vondip over 3 years

    I am developing a web application in asp.net mvc 3. I am very new to it. In a view using razor, I'd like to declare some local variables and use it across the entire page. How can this be done?

    It seems rather trivial to be able to do the following action:

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

    But this doesn't work. Is this possible?