简体   繁体   中英

Get variable value from code behind and use in aspx page control

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

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

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 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 %>' />

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

Thanks for the inspiration!

You can't usually put scriplets in server controls. But there's an easy workaround: use a plain html control:

<span id="ltrTesting"><%= this.Testing %></span>

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

ltrTesting.Text = "Hello World!";

try making Testing be a property rather than a field:

eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM