通过主页面访问内容页变量

4
我知道在ASP.net中,我们可以通过内容页访问主页面变量,但是否有任何方法可以通过主页面访问内容页变量呢?
1个回答

2

是的,您可以。您需要实现一个基类,并从该基类派生内容类。

编辑:发布标记并更改代码以提供更清晰的示例

我创建了一个基本页面,继承了System.Web.UI.Page,然后使内容页面继承它。我的基础页面:

namespace WebApplication2
{
    public class BasePage : System.Web.UI.Page
    {
        public BasePage() { }

        public virtual string TextValue()
        {
            return "";
        }

    }
}

这是我的内容页面标记:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>


<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <asp:Label ID="lblContentText" Text="Contentpage TextValue:" runat="server"></asp:Label>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:Content>

内容页面代码:

namespace WebApplication2
{
    public partial class _Default : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public override string TextValue()
        {
            return TextBox1.Text;
        }
    }
}

我的主控页面标记:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="WebApplication2.SiteMaster" %>

<!DOCTYPE html>
<html lang="en">
<head runat="server">
    <meta charset="utf-8" />
    <title><%: Page.Title %> - My ASP.NET Application</title>  
    <asp:ContentPlaceHolder runat="server" ID="HeadContent" />
</head>
<body>
    <form runat="server">    
    <header> </header>
    <div id="body">
        <asp:Label ID="lblText" runat ="server" Text="Masterpage Text :" />
        <asp:TextBox ID="txtMaster" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Click to read content page TextValue " OnClick="Button1_Click" />
        <asp:ContentPlaceHolder runat="server" ID="MainContent" />
    </div>
    <footer>
    </footer>
    </form>
</body>
</html>

在主页面代码后端的实现:

namespace WebApplication2
{
    public partial class SiteMaster : MasterPage
    {
        BasePage Currentpage = null;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Currentpage = this.Page as BasePage;
            if (Currentpage != null)
            {
                txtMaster.Text = Currentpage.TextValue();
            }
        }
    }
}

如果您看到任何错误,例如BasePase未被识别,请确保它使用相同的命名空间(即WebApplication2),或将命名空间添加到实现页面中(即使用WebApplication2;)。
希望这可以帮助您!

谢谢!但是你如何引用BasePages类?我收到了一个编译错误,指示BasePages类缺少程序集引用。编译器错误消息:CS0246:找不到类型或命名空间名称“BasePages”(是否缺少using指令或程序集引用?) - Superman Coding
你必须将它们放在同一个命名空间中,或者在主页面的代码后台中添加 using 'mybasepagenamespace';其中 mybasepagenamespace 是 BasePage 类的命名空间。我已经编辑了我的答案。 - afzalulh
尽管我不得不在命名空间上瞎折腾,但它还是能正常工作的。谢谢! - Superman Coding
CS0103:当前上下文中不存在名称为'TextBox1'的变量。 - Marco Marsala

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接