简体   繁体   English

如何将值从页面传递到用户控件?

[英]How to pass value from page to User Control?

I am using one user control in a page. 我在页面中使用一个用户控件。 Basically after login this page is coming with user control. 基本上,登录后此页面带有用户控制。 I wanted pass the user name in that user control from login page. 我想通过登录页面在该用户控件中传递用户名。

Say for you store the login name in a LABEL somewhere on the main page. 假设您将登录名存储在主页上的LABEL Like this: 像这样:

lblLogin.Text = "LoginName";

Now, on the user control you have another LABEL called lblWCLogin where you want to assign the login name from Parent page. 现在,在用户控件上,您具有另一个名为lblWCLogin的 LABEL ,您要在其中从“父”页面分配登录名。 Do something like this: 做这样的事情:

Label lblTextFromParentPageLabel = this.Parent.FindControl("lblLogin"); 
lblWCLogin = lblTextFromParentPageLabel.Text;

Another Approach (does not matter if you have a MasterPage or not) is to Use Sessions. 另一种方法(无论您是否拥有母版页都无关紧要)是使用会话。

Set session on you Page or MasterPage code behind. 在您的Page或MasterPage代码后面设置会话。 Like this: 像这样:

Session["LoginName"] = "Some User Name";

Retrive the session value on UserControl like this: 像这样检索UserControl上的会话值:

string login_name = (string)(Session["LoginName"]);
Label1.Text = login_name;

There are many ways to achieve this 有很多方法可以做到这一点

  1. As one is to find the control 一是找到控制
  2. Store value in session and set the value from that session 在会话中存储值并从该会话中设置值
  3. Create public method of user control which will set the value of your label.. and call that userControl.SetPageLabel() method from your page at your desired places.... 创建用户控件的公共方法,该方法将设置标签的值..并在所需位置的页面中调用该userControl.SetPageLabel()方法。

Make sure you have your label is in the update panel other wise label text will be changed but not visible on the screen... 确保标签在更新面板中,否则标签文本将被更改,但在屏幕上不可见...

Or you can use some javascript to set the label... 或者您可以使用一些JavaScript来设置标签...

http://center4code.com/ http://center4code.com/

There are many ways to do this. 有很多方法可以做到这一点。

My suggestion is create a Property field in the user control which allow you to read or write value from any page that refer to the user control. 我的建议是在用户控件中创建一个“属性”字段,该字段允许您从引用该用户控件的任何页面读取或写入值。

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

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