New to C # and trying to use a global variable

Is it possible to use global variables in C #? I come from the main background of PHP, so the variables are available either everywhere or simply global.

My main problem: I have a class Userthat I created to wrap the current table usersin my company database. I define it in MasterPage, but I can’t access it from real pages (I don’t know if there is a better word for their description, but these are pages that inherit the styles and format from MasterPage)

Any general tips or implementation practices for me?

EDIT : here are some code snippets of what I'm trying to do:

Site.master.cs

public partial class SiteMaster : System.Web.UI.MasterPage
{
    public User user = new User();
}

logout.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="logout.aspx.cs" Inherits="logout" %>
<%@ MasterType  virtualPath="~/Site.master"%>

logout.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        User user = Master.user;
    }
}
+3
7

, . , .

# - . , - , . (http://en.wikipedia.org/wiki/Object-oriented_programming) : , .

/-, , App_Code.

+4

-.

, - , , .

+2

Page MasterPage, User, MasterPage, Page.

+2

, , MasterPageClass .aspx :

<%@ MasterType TypeName="MyTypeName" VirtualPath="~/MasterPageName.master" %>

, . , .

User /AppCode (User.cs). , MasterType.

+2

. . , . , , .

"Session", .

+1

, ( ASP.Net MasterPage ?)

, -. , MasterPage. , , MasterPageFile MasterType, :

public partial class MasterPage
{
    public User CurrentUser{...}
}

aspx .

<%@ Page  masterPageFile="~/MasterPage.master"%>
<%@ MasterType  virtualPath="~/MasterPage.master"%>

:

var user = Master.CurrentUser;

, CurrentUser, . , MasterPage.Init .Init MasterPage.Load . MP.Init MP.Load, , , , Init.

+1

, , :

  • Use the Application Object - It can be used to store things all over the world and is part of ASP.Net.

  • Use static classes - This is another option for creating a singlet.

0
source

Source: https://habr.com/ru/post/1736515/


All Articles