Home > Back-end >  Unable to access variable in razor page
Unable to access variable in razor page

Time:10-09

I have the following razor page in my project:

@using XditProj.Models
@model List<XditProj.Models.UserViewModel>
  <link rel="stylesheet" href="../../wwwroot/css/askStyles.css">
  <link rel="stylesheet" href="../../wwwroot/css/bootstrap.min.css">
<link rel="stylesheet" href="../../wwwroot/css/bootstrap.min.css">

@foreach (UserViewModel user in @Model)
{
  @{
    var currentLocalModel = user.moneyStats;
    var one = "weekly price:";
    string two = "saved from last week:";
    string three = "yearly Spending:";
  };

  <div class="row">
    <div class="col-sm-3">
      <div class="well red">
        <p>@user.UserName </p>
      </div>
    </div>
    <div class="col-sm-9">
      <div class="well neutral">
        <p> @user.status</p>
        <div class="bottom-left-text">
          <span class="label label-default">@one  </span>
          <span class="label label-primary">Total KWH: 200</span>
          <span class="label label-success">Labels</span>
        </div>
      </div>
    </div>
  </div>
}

my question is regarding the line <span class="label label-default">@one </span> where I am trying to access the variable one that I have just declared. But my ide is freaking out and cannot find anything of that name.

Why am I unable to access the variable?

CodePudding user response:

In C# curly braces ({}) creates a new scope for variables. Variables declared in the "inner" scope are not accessible in the "outer" scope. I don't see a need to declare a new scope here, so you can just remove it:

@foreach (UserViewModel user in @Model)
{
  var currentLocalModel = user.moneyStats;
  var one = "weekly price:";
  string two = "saved from last week:";
  string three = "yearly Spending:";

  <div class="row">
  ...

You could also declare one, two, and three outside of the foreach since their values do not change, but it's not necessary to get the script to work,

  • Related