Home > Enterprise >  Can't access variables inside same block of code in Blazor
Can't access variables inside same block of code in Blazor

Time:12-23

I know this is basic but I am new to Blazor and I don't get the concept, why can't I access this variable. And if this is meant to be like this what are the benefits of this. The code is inside one block and I can't access Test.

@code{
    Service.Service1Client Client = new Service.Service1Client();
    int Test = 4;
    Test  ;
}

enter image description here

CodePudding user response:

Imagine that the @code{ says class{ instead. This is not valid C#:

class Something{

  int Test = 4;   //declares a class level variable called Test - not perfect, because it's a private field and shouldnt have a pascalCase name, but.. it works
  Test  ;         //can't run code like that in a class level context

You'll have to do that Test inside a method (maybe drop a button into the markup, put an onclick="@SomeMethodName" and put a private void SomeMethodName(){ Test ; } in the class. The Counter razor example should have some helpful code in

You can also do this (and I do this often because intellisense works so much nicer in VS2019):

Suppose you have in Solution Explorer:

Pages
 -- MyPage.razor

You can add a class called MyPage.razor.cs in the Pages folder

Pages
 -- MyPage.razor
     -- MyPage.razor.cs

It gets put as a child of MyPage.razor

Open the class and ensure it says:

public partial class MyPage{

}

Now you can just code in there instead of in the @code{ block.. All the things you're used to in a normal class will work there, and the markup razor file can be just for markup.. And best of all you won't have some minor syntax error in the markup (like too many () clobbering your @code region and creating syntax errors under every line, with all kinds of weird error messages like "does not contain a constructor with that many arguments" - the Intellisense seems to work a lot better/more tolerant of minor errors/unfinished statements if you work in a codebehind class rather than an in-page @code

  • Related