从后面的代码中获取变量值并在aspx页面控件中使用 [英] Get variable value from code behind and use in aspx page control

查看:33
本文介绍了从后面的代码中获取变量值并在aspx页面控件中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Web 用户控件,其中的控件需要从底层页面的变量或属性中获取一些数据.

I got a web user control where I have controls that needs to be fed with some data from variables or properties from the underlying page.

<%@ 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 did read this topic, but it wont solve my problem, I assume it's because this is a user control and not a page. I want to get property value from code behind

推荐答案

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

Solved this, solution below

因为我在这种情况下使用了 Web 用户控件,所以通常的情况是行不通的.但是通过在控制用户控件的页面中放置一个数据绑定,或者在 web 用户控件上方的链中的任何母页中,代码开始工作

Since I used a web user control in this case the usual scenarios would not work. But by putting a databind in the page that controls the user control, or any materpage in the chain above the web user control the code started to work

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 文件,以下所有建议的解决方案都有效

Ascx file, all suggested solutions below works

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

感谢您的启发!

这篇关于从后面的代码中获取变量值并在aspx页面控件中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆