2013-10-11 77 views
1

目的:阅读从我的aspx页面的隐藏字段值在ASCX页如何在ascx页面中声明隐藏字段,以便它从aspx中的隐藏字段获取值?

问题:我是新来的ASP,我不知道如何做到这一点。我可以在aspx页面中设置隐藏字段的值,但是如何在ascx页面中读取该值?我使用的代码如下

Page1.aspx的上述

<%@ Register Src="~/UserControl/Page2.ascx" TagName="Info" TagPrefix="uc" %> 
<asp:HiddenField ID="hdnfldInfo" runat="server" /> 

Page1.aspx.cs

String strInfo = Convert.ToString(e.CommandArgument); 
hdnfldInfo.Value = strInfo; 

Page2.ascx

HiddenField Info = (HiddenField)this.Info.FindControl("hdnfldIncDesc"); 

代码Page2上。 ascx没有相同的值。我错过了什么或做错了什么?

预先感谢您的任何意见,建议或意见

+0

其实我最终通过添加以下到第2页HiddenField信息=​​ Parent.Findcontrol( “hdnfldInfo”)作为HiddenField解决这个; –

回答

2

ascx控件提供了我们可以使用的页面。

this.Page 

现在我们需要从该页面获得控件。因为我们知道它的名字,你可以使用的FindControl

HiddenField Info = this.Page.FindControl("hdnfldIncDesc"); 

注意,这将返回null如果与该名称的控件无法找到。所以相应编码。

+1

你不能保证父页面将有一个隐藏的字段。这使得用户控制非常有限,这不是最佳实践 –

3

您需要在ASCX创建一个属性(也称为用户控制),并有基于隐藏字段设置该属性aspx页面

让你的ASCX后面的代码是这样的:

public class MyUserControl : UserControl{ 
    public String MyProperty {get;set;} 

    //...do stuff with myProperty 

} 

,然后在后面

public class MyPage : Page{ 
    protected void Page_Load(){ 
     HiddenField info = (HiddenField)myHiddenField; 
     MyUserControl control = myusercontrol; 
     control.MyProperty = info.Value; 
    } 

} 
aspx页面代码

您可能需要更改该属性设置的页面生命周期的哪一部分。

我也会看看一些关于创建用户控件的文章,因为您是asp.net的新手。它会在以后付清。

看看: 好文章在gernal有关创建用户控件:http://msdn.microsoft.com/en-us/library/3457w616(v=vs.100).aspx(跳到添加自定义属性和方法,为相关问题的用户控制部分)

send custom parameters to user control ascx有一个好的例子

+0

'info.Value'? .Text用于文本框... – 2013-10-11 16:50:44

+0

@ebyrob感谢并更新 – Letseatlunch

+0

为什么将myusercontrol对象强制转换为MyUserControl?没有必要这样做。 –

2

您需要从用户控件访问父页面,除了将隐藏的字段设置为公开并且不需要保护(默认情况下),方法是进入设计器代码。最佳做法是在用户控件中创建一个属性,然后由父级用户控件设置该属性,然后用户控件将使用该属性将其显示在页面上。

// usercontrol: 

public string MyProperty {get; set;} 

// ASPX page: 
this.ucMyUserControl.MyProperty = this.hdnfldInfo.Value; 

然后在您的用户控件中,只要您认为合适,就使用“MyProperty”。

+0

在页面流中你会做这个任务吗?在里面?加载?别处? – 2013-10-11 16:49:01

+0

尽管您可以从用户控件访问父页面,但不应该依赖此页面,因为您无法保证父页面将具有隐藏字段。这使得用户控制非常有限,这不是最佳实践 –

+0

@ebyrob - 无论你喜欢什么。 –

0

使用this.Parent.FindControl(HiddenBankAccountId)