简体   繁体   English

如何在页面加载时将值从用户控件传递到ASPX页面?

[英]How to pass value from user control to aspx page on pageload?

The scenario is very simple. 场景非常简单。 I have an aspx page with a user control. 我有一个带用户控件的aspx页面。 I want to set a value and get a response from usercontrol on aspx page's pageload. 我想设置一个值,并从aspx页面的页面加载上的usercontrol获得响应。 The SET job is done, but can't GET the response. SET作业已完成,但无法获取响应。 It's always empty. 它总是空的。 I tried two methods, but none of them worked. 我尝试了两种方法,但没有一种有效。

ASPX PAGE ASPX页面

<uc1:ucContent ID="Content1" runat="server" />

CODE BEHIND 后面的代码

protected void Page_Load(object sender, EventArgs e)
{
    // SET job is working without any problem
    Content1.ItemName = "X";

    //METHOD ONE:
    Page.Title = Content1.MetaPageTitle;

    //METHOD TWO:
    HiddenField hdnPageTitle = (HiddenField)Content1.FindControl("hdnMetaPageTitle");
    Page.Title = hdnPageTitle.Value;
}

USER CONTROL 用户控制

protected void Page_Load(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(itemName))
    {
         // GET DATA FROM DB

         // METHOD ONE:
         hdnTitle.Value = DB.DATA;

         // METHOD TWO:
         metaPageTitle = DB.DATA;
    }
}

private string metaPageTitle;
public string MetaPageTitle
{
    // METHOD ONE:
    get { return metaPageTitle; }

    // METHOD TWO:
    get { return hdnTitle.value; }
}

EDIT 编辑

itemName is a UserControl property to get a value from Parent Page: itemName是一个UserControl属性,用于从父页面获取值:

private string itemName;
public string ItemName
{
    set { itemName = value; }
}

Thanks for your kind help in advance! 感谢您的提前帮助!

I think that the problem is that the page 's Page_Load is triggered before the UserControl (Have a look: asp.net: what's the page life cycle order of a control/page compared to a user contorl inside it? ). 我认为问题在于pagePage_Load是在UserControl之前触发的(看看: asp.net:与控件内部的用户控件相比,控件/页面的页面生命周期顺序是多少? )。

So you could set the property in Page_init : 因此,您可以在Page_init设置属性:

In your UserControl : 在您的UserControl

protected void Page_Init(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(itemName))
    {
         // GET DATA FROM DB

         hdnTitle.Value = DB.DATA;
    }
}

Now this should work in your page's Page_Load : 现在,这应该可以在您页面的Page_Load

Page.Title = Content1.MetaPageTitle;

Normally i would prefer another kind of communication between a Page and a UserControl. 通常,我希望在Page和UserControl之间进行另一种通信。 It's called event-driven communication and means that you should trigger a custom event in your UC when the MetaPageTitle changed (so in the appopriate event-handler). 这称为事件驱动的通信,这意味着当MetaPageTitle更改时(因此在适当的事件处理程序中),您应该在UC中触发自定义事件。

Then the page can handle this specific event and react accordingly. 然后页面可以处理此特定事件并做出相应反应。

Mastering Page-UserControl Communication - event driven communication 掌握页面-用户控制通信-事件驱动的通信

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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