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

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

问题描述

我有一个网页用户控件,其中有控件需要从基础页面的变量或属性中提供一些数据。

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" />

Codebehind

Codebehind

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

推荐答案

解决此问题,

由于我使用了网络用户在这种情况下控制通常情况将不起作用。但是通过在控制用户控件的页面中放置一个数据库,或者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 codebehind

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

感谢您的灵感!

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

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