从代码中获取变量值并在aspx页面控件中使用

我有一个Web用户控件,我有控件需要从底层页面的变量或属性中提供一些数据。

 <asp:Literal runat="server" Text='' 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 } } } 

我确实读过这个主题,但它不会解决我的问题,我认为这是因为这是一个用户控件,而不是一个页面。 我想从代码中获取属性值

解决了这个,解决方案如下

由于在这种情况下我使用了Web用户控件,因此通常的方案不起作用。 但是通过在控制用户控件的页面中放置数据绑定,或者在Web用户控件上方的链中的任何materpage,代码开始工作

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:  2:  3:  

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) { } } } 

感谢您的灵感!

您通常不能将scriplet放在服务器控件中。 但是有一个简单的解决方法:使用普通的html控件:

 <%= this.Testing %> 

或者您可以在后面的代码中设置Literal的Text属性:

 ltrTesting.Text = "Hello World!"; 

尝试使测试成为属性而不是字段:

例如

 public string Testing { get { return "Hello World!"; } }