Search code examples
c#asp.netsessionmaster-pagescontent-pages

How to pass value from masterpage to contentpage ASP.Net C#


I have a login button in my masterpage, after I successfully logged in, I wish to pass the value of my loggedUserName to my content page, helps and suggestions are much appreciated!

Referred to the following forum, no idea how to continue: http://forums.asp.net/t/1758733.aspx?Passing+Value+from+Master+page+to+Content+Page

EDITTED: (below are my code in masterpage)

public partial class MasterPage : System.Web.UI.MasterPage
{
    SqlCommand SQLSelect = new SqlCommand();
    SqlConnection SQLCon = new SqlConnection();
    DataTable dt = new DataTable("Customer");
    int len;


protected void Page_Load(object sender, EventArgs e)
{
    SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings["SDMConnectionString"].ConnectionString;
    SQLCon.Open();
    SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customer", SQLCon);
    len = da.Fill(dt);

    string checking = Request.QueryString["user"];

    if (checking != null)
    {
        memberview.Visible = true;
        userview.Visible = false;
    }
    else
    {
        userview.Visible = true;
        memberview.Visible = false;
    }

    lblLoggedUser.Text = "(" + checking + ")";
}
protected void LoginButton_Click(object sender, EventArgs e)
{
    string username = UserName.Text;
    string pass = Password.Text;
    int counter = 0;
    string content = @"category.aspx?content=" + username;


    foreach (DataRow row in dt.Rows)
    {
        string usernameCheck = row["Username"].ToString();
        string passCheck = row["Pass"].ToString();

        if (username == usernameCheck && pass == passCheck)
        {
            counter = 1;

            Response.Redirect(content);
            break;

        }
        else
        {
            counter = 0;
        }

    }

    if (counter == 1)
    {

        Session["user"] = username;
        lblLoggedUser.Text = Session["user"].ToString();

    }
    else
    {
        HttpContext.Current.Response.Write("<script>alert('Error Username or Password!');</script>");
    }

}

}


Solution

  • One way is to use the master parameter on Page and read anything public from master page. Here's an example

    Master Page

    public partial class cMasterPage : System.Web.UI.MasterPage
    {
        public string getUserName
        {
            get
            {
                return "what ever";
            }
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    }
    

    Page

    public partial class cPage : System.Web.UI.Page
    {    
        protected void Page_Load(object sender, EventArgs e)
        {
            string cGetValue = ((cMasterPage)Master).getUserName;
        } 
    }