I have a page and clicked on the button there it will open a new page containing some text boxes, user fill all the text boxes and clicked the button now first page open again and the question is : How can I get the vales of text boxes on the current page using both server-side and client-side
There is a restrictions to use of :
- Cross-paging
- Cookies
- Sessions
- Query strings
Server-side approach:
An alternate approach is to use Server.Transfer method.
On the current page:
protected void Transfer_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Server.Transfer("destination.aspx");
}
}
On the destination page:
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox textBox = PreviousPage.FindControl("Parameter")
as TextBox;
if (textBox != null)
{
string parameter = textBox.Text;
Parameter.Text = parameter;
}
}
}
But Server.Transfer does come with disadvantages. The most serious is that the URL in the browser does not change. The browser still believes it has posted back and received content for the first web form, so history and book-marking suffer.
Client-side approach:
In real world I don't recommend to use this solution, this is only a workaround.
In two words: use window.name property on the client side. This property is available across page reloads it is a sort of session.
For more information see:
What’s in a window.name?
window.name Transport
Hope, this helps.
If you are using the PostBackUrl property of the button on the submitting page, you can access the controls for the "previous page" from the action page by using the following:
Dim txtBox as TextBox
txtBox = CType(Page.PreviousPage.FindControl("MyTextBox"), TextBox)
Then you'll have access programmatically to all of the properties and data for that control.
Use the cache if you can't use the Session, Querystring, Cookies and Cross Page posting.
If it is simple/primitive data, then you can go for the ViewState. Or Cache is a better option.
One more option is to have a Page level public variables, set the required values and redirect to the page for further processing.(This is not a good approach to follow)
Related
I have in Site.Master:
<% if(Session["msg"]!=null) Response.Write(Session["msg"].ToString()); %>
I have also on submit form method:
protected void Send_Click(object sender, EventArgs e)
{
Session["msg"] = "Thx for email.";
Response.Redirect("~/Default.aspx");
}
But now when I refresh page or go to another page I still see "Thx for email." but user should see it only once.
You can clear out the Session["msg"] on Page_load (outside of the if(!isPostback))
Or you can create a label on the master page, access that through the child pages to put the message in there, and clear that one on Page load, this gets you away from using Session. Using a Label you can also set the cssClass, allowing bolding, color changes (red for errors, green for success, etc).
If you just want a plan message you could aways go with a literal control, less over head.
This is because Session variable having their value throghout the session.
Session["msg"]
will always have same value on all the pages in a session.
If you want that value should only be used for the page where you redirect then you can use querystring.
protected void Send_Click(object sender, EventArgs e)
{
Session["msg"] = "Thx for email.";
Response.Redirect("~/Default.aspx?msg='true'");
}
then on SiteMaster
<% if(Request.QueryString["msg"]!=null) Response.Write(Session["msg"].ToString()); %>
You have to set Session["msg"] = null after you show the message. Session lives in server at defualt of 20 min. If you do not set it null it will appeear
Try setting the Session["msg"] to null once it is printed on the page.
I'm using a single page for two different purposes. By default it has one behavior and on coming to same page after redirecting via a link button it has a different behavior, like changing master page, etc...
How can I detect this and change the behavior accordingly?
If you have one page with two different behaviours then I would suggest that you want something like a querystring parameter to differentiate between the two purposes (eg somepage.aspx?mode=changeMaster). You can then check for this value and change your behaviour accordingly.
If you are only every doing the second behaviour from one place then its probably easiest to let it have a default behaviour rather than requiring the mode parameter (so you wouldn't have to change all your links to the page, just that one linkbutton). This should be much more reliable than relying on referrers and other such things which aren't always sent.
Use HttpRequest.UrlReferrer Property
You can know the page where you come from with the referer field that comes in the header. In asp.net you can retrieve it like this:
string MyReferrer;
if(Request.UrReferrer != null)
{
MyReferrer = Request.UrlReferrer.ToString();
}
I don't know asp.net but I'm pretty shure you can get it from the HTTP-headers referer/referrer field.
http://en.wikipedia.org/wiki/HTTP_referrer
Assuming you have control over the pages that a user redirects to and from, set a Session variable when you perform an action that your page should base its behavior upon.
For instance, in a LinkButton_Click event, you could set a Session variable like so:
protected void LinkButton_Click(object sender, EventArgs e)
{
Session["Source"] = "MyLinkButton";
}
And in your page's Page_Load or Page_Init event, check the value of that Session variable and perform the page's change in behavior based on the value in that Session variable.
protected void Page_Init(object sender, EventArgs e)
{
if (Session["Source"] == "MyLinkButton")
{
// do something
}
else if (Session["Source"] == "SomethingElse")
{
// dome something else
}
}
My apologies in advance for posting such a lengthy question. Believe it or not, what you see here actually represents a fairly condensed version of the problem/code at hand. And while I would appreciate any pointers on a better or different approach, I would also very much like to get the bottom of this so that I can sleep at night :)
I came across a requirement to pass confirmation messages between distinct aspx pages. I opted against using a query string variable since query string values "are" sticky (i.e. they persist on all subsequent postbacks) and I didn't want to deal with adding a bunch of conditional logic around this.
Anyway, I came up with a very simple class that uses Session to associate notifications with specific URLs. I then hooked my master page Page_Load event to query this class for any notifications that should be displayed for the current URL. If it finds any, it dynamically loads a NotificationMessage user control and displays the message content.
Everything works as expected when trying to pass Notifications between different aspx pages. Predictably, things don't work when a content page attempts to add a notification to itself (i.e. "The data you entered is not valid, try again"). The reason is pretty clear: by the time a content page adds a Notification for itself, the Page_Load event of the master page has already fired, so it's too late in the page lifecycle to do any good. The relevant code is pasted below.
public class MyMasterPage:MasterPage{
protected void Page_Load(object sender, EventArgs e)
{
LoadNotifications(this.Request.Url.ToString());
}
private void LoadNotifications(string url)
{
//look for a notification
Notification? notification = NotificationManager.Instance.RetrieveNotification(url);
//there are no notifications, nothing to see here
if (!notification.HasValue)
{
return;
}
//there is a Notification for this url, so load it into a user control
NotificationMessage notificationMessageControl = (NotificationMessage)LoadControl("~/App_UserControls/NotificationMessage.ascx");
notificationMessageControl.ID = "notificationMessage";
notificationMessageControl.Notification = notification;
notificationMessageControl.Visible = true;
//find the placeholder on the master page
PlaceHolder placeHolder = (PlaceHolder)PageUtils.FindControlRecursive(this, "NotificationPlaceholder");
if (placeHolder == null)
{
throw new ApplicationException("NotificationPlaceholder control not found.");
}
//insert into control
placeHolder.Controls.Add(notificationMessageControl);
placeHolder.Visible = true;
//remove the notification so it doesn't show up next time
NotificationManager.Instance.RemoveNotification(url);
}
}
Given the lifecycles issued alluded to above, I modified the NotificationManager class so that it raises an event whenever a notification has been added for the current page. The master page intercepts that event, and if the Page_Load has already fired, it kicks off the LoadNotifications method all over again.
//bind the event on the page constructor
public MyMasterPage()
{
NotificationManager.Instance.NotificationAdded += this.NotificationAdded;
}
private void NotificationAdded(string forUrl)
{
if (_pageLoaded){
LoadNotifications(forUrl);
}
}
Unfortunately, this doesn't work. I have stepped through this code numerous times, and despite the fact that the master page loads the NotificationMessage UserControl and adds it to the appropriate placeholder without incident, the final aspx HTML never includes the markup for that UserControl. I've put breakpoints inside the Page_Load of the UserControl and verified that they are indeed being hit during execution.
If I dynamically load the UserControl from inside the content page and bypass the Master page altogether, it renders without a hitch:
public partial class MyContentPage:Page
{
public void DoSomethingCool(object sender, EventArgs e)
{
if (MyServiceLayer.Save(foo)==false){
Notification notification = new Notification(NotificationType.Error, "We’re sorry, your document was not saved.");
NotificationMessage notificationMessage = (NotificationMessage)LoadControl("~/App_UserControls/NotificationMessage.ascx");
notificationMessage.Notification = notification;
notificationMessage.Visible = true;
PlaceHolder holder = (PlaceHolder)PageUtils.FindControlRecursive(this, "NotificationPlaceholder");
holder.Controls.Add(notificationMessage);
}
}
}
For the record, I stripped out the dynamic loading of the UserControl, opting instead for a a static declaration in the master page markup and a code based toggle of the control's Visible property; still no dice!
If someone could shed some light on this conundrum, I would be much obliged.
I've tried this sort of thing before and I was never fully comfortable with it. What I did instead, was put my ASCX on every page (or on the masterpage), and let the ASCX control its state rather than letting the ASPX control my ASCX.
I'm not sure this will help for your situation, though.
It seems like you want your information to show up after your control events fire. You might consider letting those messages aggregate until all control events have fired and then pull out all of the messages from your NotificationManager in OnPreRender, rather than Page_Load. That way you can get rid of the events (like NotificationAdded), etc that are probably complicating matters.
Not 100% what the problem is, though. It sometimes helps to know that the MasterPage is actually a control on the Page, rather than the other way around like you would think. It is going to be subject to the limitations any control would have on a Page.
HTH, Anderson
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!
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();
// 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.
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 ");
...
}
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;
}
}
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"] %> !
I have a gridview button that I programmatically created and I want to load an update panel on the client side with the sent data. I have a hidden value field that gets its data on the click of the gridview button and the dropdownlist in my updatepanel depends on that value.
while calling __doPostBack directly will work, it's not a perfect solution because the name of that function is strictly speaking an implementation detail of the .Net framework.
A better solution is to use ClientScriptManager.GetPostBackEventReference, which gives you a more resilient interface to the same functionality. Do note that GetPostBackEventReference and GetCallBackEventReference are not the same thing - the former causes a page reload (partial or full, depending on how your UpdatePanels are set up), while the latter doesn't.
The easiest way to do this is to call __doPostBack from client side.
On client side button1_onclick method, calls:
__doPostBack('<%=UpdatePanel1.ClientID %>','Refresh:0,1,2'); //refresh update panel
On page behind add the following event handler to capture the post back call:
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
string arg = Request.Form["__EVENTARGUMENT"];
if (string.IsNullOrEmpty(arg)) return;
if (arg.StartWith("Refresh")
{
//parse data first then do your thing here...
}
}
And of course don't forget to wire event to the above method:
protected void Page_Init(object sender, EventArgs e)
{
UpdatePanel1.Load += new EventHandler(UpdatePanel1_Load);
}
we use the __dopostback() method which simulates a postback and causes the updatepanel to refresh
__doPostBack('controlName','');
Don't forget that the control name is it's HTML ID (which may well contain dollars etc) and not just it's ASP.NET ID.
As far as I know you can either call this method and pass in the hidden value field, or the div that it is in.