【问题标题】:How to access Control (div) in MasterPage from separate Class file如何从单独的 Class 文件访问 MasterPage 中的 Control (div)
【发布时间】:2015-10-17 01:57:28
【问题描述】:

我有 MP.Master、default.aspx、MyClass.cs

MP.Master 中有一个 div,其属性为 "runat=server"

在 default.aspx.cs 中,我调用 MyClass.cs 文件中的 MyMethod()

我无法访问 div,无法在 MyMethod() 中使用。我如何从 MyClass.cs 访问它?

【问题讨论】:

  • 我无法在内容页面中添加 MasterType 指令,因为 MyMethod() 位于单独的 MyClass.cs 文件中。
  • 如果在内容页面中添加 MasterType 指令,访问 div 控件,并将其作为参数传递给 MyMethod 会怎样。这对您来说是一个可行的选择吗?
  • @user 您有机会尝试解决方案吗?如果是这样,它对你有用吗?

标签: c# asp.net class webforms master-pages


【解决方案1】:

我测试了我的评论并确认它有效。这是一个快速示例。它将您的 div 的 innerHTML 的文本更改为“测试”。

母版页中的Div(MP.Master):

<div runat="server" id="myDiv"></div>

母版页 (MP.Master.cs) 代码中的属性:

public HtmlGenericControl TheDiv {
    get { return myDiv; }
}

您的 aspx 页面顶部的 MasterType 指令:

<%@ MasterType virtualpath="~/MP.Master" %>

该页面背后的代码(您可以将其放在按钮单击、页面加载等中):

TestClass test = new TestClass();
test.MyMethod(Master.TheDiv);

TestClass(TestClass 就像你的 MyClass):

public class TestClass
{
    public void MyMethod(HtmlGenericControl div)
    {
        div.InnerHtml = "Test";
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 2019-05-30
    相关资源
    最近更新 更多