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

倾然丶 夕夏残阳落幕 提交于 2019-11-29 07:17:21

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>

Or you could set the Text property of the Literal in the code behind:

ltrTesting.Text = "Hello World!";

try making Testing be a property rather than a field:

e.g.

public string Testing
{
    get { return "Hello World!"; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!