Search code examples
c#master-pageswebmethod

Get Master Page Control Value In Content Page static webmethod in c#


I can fetch MasterPage control value in Content Page

but I can't understand how to fetch MasterPage control value in Content Page in static webmethod

on google, I found many interesting articles but all of them use ajax and jquery technology

but ajax and jquery is not suitable for me in this case

any suggestions, please?

my code below

masterpage

public partial class MasterPage : MasterPage
{
    public string UserNamePropertyOnMasterPage
    {
        get
        {
             // Get value of control on master page
             return lblUserName.Text;
        }
        set
        {
            // Set new value for control on master page 
            lblUserName.Text = value;
        }
    }
}

    <form id="form1" runat="server">
        <div>
            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>
            <span style="font-size: 25px; background-color: greenyellow">
                <asp:Label ID="lblUserName" runat="server" Text="Shazam"></asp:Label>
            </span>
    </form>

code-behind of Default.aspx.cs

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            lblCurrentUserName.Font.Size = 20;
            lblCurrentUserName.BackColor = Color.Yellow;
            lblCurrentUserName.Text = "Value Received in Content Page : " + Master.UserNamePropertyOnMasterPage;
        }
    }

    [WebMethod(EnableSession = true)]
    [ScriptMethod]
    public static void SetLabel(string UserNamePropertyOnMasterPage)
    {
        HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();

        Label Hname = (Label)Master.UserNamePropertyOnMasterPage;
        lblCurrentUserName.Text = Hname;
    }
}

markup of Default.aspx

<%@ Page Title="" Language="C#" MasterPageFile="MasterPage.master" 
    AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ MasterType VirtualPath="MasterPage.master" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <asp:Label ID="lblCurrentUserName" runat="server" Text=""></asp:Label>
</asp:Content>

Solution

  • It is not possible to call a master page method from a static web method. This is a fundamental concept to understand in C#. Basically the master page does not exist during the web request. Only the web method is called.

    Use JavaScript/jQuery to update the current page HTML.