在 C# 中的内容页面静态 web 方法中获取母版页控件值

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

我可以在Content Page

中获取MasterPage控制值

但我无法理解如何在 static webmethod

中获取 Content Page 中的 MasterPage 控制值

在google上,我发现了很多有趣的文章,但它们都使用了ajaxjquery技术

但是ajaxjquery不适合我这种情况

有什么建议吗?

下面是我的代码

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>

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;
    }
}

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>

无法从静态 Web 方法调用母版页方法。这是在 C# 中需要理解的基本概念。基本上在网络请求期间母版页不存在。只调用了web方法。

使用JavaScript/jQuery更新当前页面HTML。