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

标签 c# data-binding webusercontrol

我有一个 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/

相关文章:

wpf - 在 TextBlock 中使用绑定(bind)硬编码文本

asp.net - 如何在aspx页面中查找用户控件的id

c# - 如何使用生产者/消费者队列递归搜索文件夹和文件?

c# - TypeConverter 行为不一致?

c# - Visual Studio 中的基本 Winforms 数据绑定(bind)(设计器模式)

c# - 虚拟机的 UWP MVVM 数据绑定(bind)(来自字符串的 textbox.text)

c# - 从此方法返回的最佳对象 asp.net csharp

ubuntu - 无法以网络用户身份运行 oowriter

c# - 从 C# 中调用 StrFormatByteSize64 函数

c# - 异步和并行下载文件