using sessions in asp.net

為{幸葍}努か 提交于 2019-12-10 10:39:47

问题


I would like the data that i enter in a text box on pageA to be accessable on pageB

eg: User enters their name in text box on page A

page B says Hello (info they entered in text box)

I heard this can be accomplished by using a session but i don't know how.

can someone please tell me how to setup a session and how to store data in it? Thank you!


回答1:


Session["valueName"]=value; 

or

Session.Add("valueName",Object);

And You can retrieve the value in label (for Example) By

/*if String value */     
Label1.Text=Session["valueName"].ToString();

or

Label1.Text=Session.item["valueName"].ToString();

And also You can remove the session by;

/*This will remove what session name by valueName.*/
 Session.Remove( "valueName"); 

/*All Session will be removed.*/ 
Session.Clear(); 



回答2:


// Page A on Submit or some such
Session["Name"] = TextBoxA.Text;

// Page B on Page Load
LabelB.Text = Session["Name"];

Session is enabled by default.




回答3:


Yes, you could do something like JohnOpincar said, but you don't need to.

You can use cross page postbacks. In ASP.Net 2.0, cross-page post backs allow posting to a different web page, resulting in more intuitive, structured and maintainable code. In this article, you can explore the various options and settings for the cross page postback mechanism.

You can access the controls in the source page using this code in the target page:

protected void Page_Load(object sender, EventArgs e)
{
    ...
    TextBox txtStartDate = (TextBox) PreviousPage.FindControl("txtStartDate ");
    ...
}



回答4:


You can use session to do this, but you can also use Cross Page Postbacks if you are ASP.NET 2.0 or greater

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

if (Page.PreviousPage != null) {
    TextBox SourceTextBox = 
        (TextBox)Page.PreviousPage.FindControl("TextBox1");
    if (SourceTextBox != null) {
        Label1.Text = SourceTextBox.Text;
    }
}



回答5:


There is even a simpler way. Use the query string :

In page A :

<form method="get" action="pageB.aspx">
    <input type="text" name="personName" />
    <!-- ... -->
</form>

In page B :

Hello <%= Request.QueryString["personName"] %> !


来源:https://stackoverflow.com/questions/898990/using-sessions-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!