我有一个 Web 用户控件,我的控件需要从底层页面的变量或属性中获取一些数据。
<%@ Control Language="C#" AutoEventWireup="False" CodeFile="Header.ascx.cs" Inherits="Site.UserControls.Base.Header" %>
<asp:Literal runat="server" Text='<%# Testing %>' id="ltrTesting" />
代码隐藏
namespace Site.UserControls.Base
{
public partial class Header : UserControlBase
{
public string Testing = "hello world!";
protected void Page_Load(object sender, EventArgs e)
{
//this.DataBind(); // Does not work
//PageBase.DataBind(); // Does not work
//base.DataBind(); // Does not work
//Page.DataBind(); // Does not work
}
}
}
我确实阅读了这个主题,但它不能解决我的问题,我认为这是因为这是一个用户控件而不是页面。 I want to get property value from code behind
最佳答案
解决了这个问题,下面是解决方案
由于我在这种情况下使用了 Web 用户控件,因此通常的场景将无法正常工作。但是通过在控制用户控件的页面中放置数据绑定(bind),或者在网络用户控件上方的链中的任何母页中,代码开始工作
MasterPage 代码隐藏
public partial class MasterPages_MyTopMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
// Databind this to ensure user controls will behave
this.DataBind();
}
}
Ascx 文件,下面所有建议的解决方案都有效
<%@ Control Language="C#" AutoEventWireup="False" CodeFile="Header.ascx.cs" Inherits="Site.UserControls.Base.Header" %>
1: <asp:Literal runat="server" Text='<%# DataBinder.GetPropertyValue(this, "Testing") %>' />
2: <asp:Literal runat="server" Text='<%# DataBinder.Eval(this, "Testing") %>' />
3: <asp:Literal runat="server" Text='<%# Testing2 %>' />
ascx的代码隐藏
namespace Site.UserControls.Base
{
public partial class Header : UserControlBase //UserControl
{
public string Testing { get { return "hello world!"; } }
public string Testing2 = "hello world!";
protected void Page_Load(object sender, EventArgs e)
{ }
}
}
感谢您的启发!
关于c# - 从代码后面获取变量值并在 aspx 页面控件中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8883262/