【问题标题】:How is a hidden field declared in ascx page so that it takes value from hidden field in aspx?ascx 页面中如何声明隐藏字段,以便从 aspx 中的隐藏字段中获取值?
【发布时间】:2014-08-22 17:55:09
【问题描述】:

目标:从我的 ascx 页面中的 ascx 页面中读取隐藏字段值

问题:我是 ASP 新手,不知道如何完成。我可以在 asx 页面中设置隐藏字段的值,但是如何在 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 上面的代码没有相同的值。我错过了什么或做错了什么?

提前感谢您的任何 cmet、建议或建议

【问题讨论】:

  • 我实际上通过将以下内容添加到 page2 HiddenField Info = Parent.Findcontrol("hdnfldInfo") as HiddenField; 来解决这个问题;

标签: c# asp.net


【解决方案1】:

您需要在 ascx(也称为用户控件)上创建一个属性,并让 aspx 页面根据隐藏字段设置该属性

让你的 ascx 代码像这样:

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

     //...do stuff with myProperty

}

然后在aspx页面代码后面

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

}

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

由于您是 asp.net 的新手,我还想查看一些有关创建用户控件的文章。以后会有回报的。

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

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

【讨论】:

  • 为什么要将 myusercontrol 对象转换为 MyUserControl?不需要这样做。
  • @Ahmedilyas good call 更新了示例。但为了记录,这只是一个粗略的例子来展示这个想法。
【解决方案2】:

ascx 控件有一个对我们可以使用的页面的引用。

this.Page

现在我们需要从该页面获取控件。由于我们知道它的名称,您可以使用 FindControl

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

请注意,如果找不到具有该名称的控件,这将返回 null。所以相应地编码。

【讨论】:

  • 您不能保证父页面会有隐藏字段。这使得用户控制非常有限,这不是最佳做法
  • @DavidWork - 旧线程,但如果您是编写页面的人,您可以保证页面会有一个隐藏字段;这是一种笨拙的方式,但在某些情况下,这正是我们所需要的
【解决方案3】:

您需要从用户控件访问父页面,此外还需要通过进入后面的设计器代码将该隐藏字段设为公开且不受保护(默认情况下)。最佳实践是在父级设置它的用户控件中创建一个属性,然后用户控件将使用相关属性在页面上显示它。

// usercontrol:

public string MyProperty {get; set;}

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

然后在您的用户控件中,在任何您认为合适的地方使用“MyProperty”。

【讨论】:

  • 您会在页面流中的哪个位置执行此任务?在里面?加载?其他地方?
  • 虽然您可以从用户控件访问父页面,但您不应该依赖它,因为您不能保证父页面会有隐藏字段。这使得用户控制非常有限,这不是最佳做法
  • @ebyrob - 随心所欲。
【解决方案4】:

使用 this.Parent.FindControl(HiddenBankAccountId)

【讨论】:

    猜你喜欢
    • 2014-04-10
    • 1970-01-01
    • 2013-04-06
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多