Home > Software engineering >  C# Razor Pages, Accessing variable from an instantiated class instantiated from another class that i
C# Razor Pages, Accessing variable from an instantiated class instantiated from another class that i

Time:11-30

I have a class with a variable in it. I instantiate that class from another class and instantiate that class from Index.cshtml.cs. I'm trying to access the variable in the original class from Index.cshtml however I'm getting various error depending on the word combinations I try.

Class

public class Aclass
{
    public string AString;
}

public class Bclass
{
    Aclass A1= new Aclass ();
}

Index.cshtml.cs

public void OnGet()
{
    Bclass DataRaw = new Bclass();
}

Index.cshtml

How do I access AString from the Razor page?

1 example: @IndexModel.DataRaw.AString - error: IndexModel does not contain a definition of DataRaw. etc

I realise this is a very basic question but I have only ever seen information about 1 level of instantiation.

CodePudding user response:

The variable DataRaw is currently in the scope of the OnGet function, meaning that is the only place the variable is accessible. Move the variable outside of the function, into the class body.

public class Index : PageModel
{
    public Bclass DataRaw { get; set; } = new Bclass();

    ...
}

You also need to make A1 inside of Bclass public in order to access it.

public class Bclass
{
    public Aclass A1 = new Aclass();
}

Then access your variable in the cshtml page

<p>
    @Model.DataRaw.A1.AString
</p>
  • Related