【问题标题】:Accessing a value in a user control inside a content page from a master page从母版页访问内容页内的用户控件中的值
【发布时间】:2016-10-25 09:23:56
【问题描述】:

我在内容页面内的用户控件 (ascx) 中有一个字符串 (lang)。我想从母版页访问(语言)值。我该怎么做?

用户控制 (lang.ascx.cs) - 代码隐藏。

 lang = (string)(Reader["lang"]); //lang is retrieved from a database

用户控制 (lang.ascx)。

<input runat="server" type="hidden" ID="langInput" value="<%: lang %>"/>

内容页面 (lang.aspx)

<uc:lang runat="server" /> 

现在如何从母版页访问 (lang) 值?

谢谢。

【问题讨论】:

  • “我如何从母版页获取 (lang) 值”你想从你想要读取的 MasterPage 中分配这个值吗?
  • 读取它以便将其发送到母版页上的另一个用户控件
  • 将此值设置为某个隐藏控件或会话变量,并在母版页 Page.Master.FindControl('controlID') 或 Session["key"] 中访问它;

标签: c# asp.net user-controls


【解决方案1】:

要找到那个控制你必须做很多FindControls

//first find the ContentPlaceHolder on the Master page
ContentPlaceHolder contentPlaceHolder = this.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;

//then the PlaceHolder on the aspx page that contains the UserControl
PlaceHolder placeHolder = contentPlaceHolder.FindControl("PlaceHolder1") as PlaceHolder;

//then the UserControl
UserControl userControl = contentPlaceHolder.FindControl("UserControl1") as UserControl;

//and finally the Control we want to manipulate
HiddenField hiddenField = userControl.FindControl("HiddenField1") as HiddenField;

hiddenField.Value = lang;

//or you can you do the same in a single line of code
HiddenField hiddenField = this.FindControl("ContentPlaceHolder1").FindControl("PlaceHolder1").FindControl("UserControl1").FindControl("HiddenField1") as HiddenField;

如果您将 UserControls 动态添加到页面,请不要忘记 分配一个 ID,否则 FindControl 将不起作用。

myControl = (MyControl)LoadControl("~/MyControl.ascx");
//do not forget to assign an ID
myControl.ID = "UserControl1";
PlaceHolder1.Controls.Add(myControl);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 2014-09-20
    • 2020-01-14
    相关资源
    最近更新 更多