如何在ASP.NET C#中的用户控件之间传递值

时间:2012-04-14 05:40:29

标签: c# asp.net sql-server-2008 entity-framework

我的页面中有3个用户控件。其中一个用户控件是关于fileUploading,第二个是关于fileUploade关键字。当文件上传时,fileUploading usercontrol返回记录该插入的Id。现在我想在fileUploaded关键字中使用此id,但是当插入标签以查看fileuploading中的id时,用户控件显示右侧id例如1或2或..但在关键字usercontrol中仅显示0值。我使用实体框架工作。如何在关键字用户控件中访问此ID。 感谢。

2 个答案:

答案 0 :(得分:2)

会话变量可能是最好的方法:

http://msdn.microsoft.com/en-us/library/ms178581.aspx

答案 1 :(得分:0)

您可以使用委托将ID传递回父页面。当id传递回父页面时,您在父页面上运行一个函数,该函数调用关键字usercontrol上的公共函数。

因此,在您的Uploading usercontrol上,首先创建父页面将侦听的委托:

public delegate void PassIDToParent(string ID);
public event PassIDToParent PassID;

接下来,一旦你返回了id,就触发委托:

protected void Upload() //--- this is your current upload function
{
    //--- other upload code
    string ReturnedID = "1"; //--- whatever is returned
    PassID(ReturnedID);
}

现在您需要在父页面上设置侦听器。一旦监听器执行,它将执行“PassID”功能。在此函数中,您将调用关键字usercontrol的公共函数“LoadID”。所以在父页面上,执行以下操作:

protected void Page_Load(object sender, EventArgs e)
{
    //--- setup the listener to receive the uploaded id
    UploadUserControlID.PassID += new UploadUserControlID_ClassName.PassIDToParent(PassID);
}
protected void PassID(string id)
{
    //--- this method is called from the listener above and it passes the id
    KeywordUserControlID.LoadID(id);
}

关键字usercontrol的代码如下所示:

public void LoadID(string id)
{
    //--- do whatever you need to with the id
}

以下是有关代表使用的更多信息:http://webdeveloperpost.com/Articles/Return-value-from-user-control-in-ASP-NET-and-C-Sharp.aspx

希望有所帮助!祝好运!不要忘记标记为答案!