I have two pages in ASP.NET 3.5 and I need to access/read the web controls values from the first page but on the second page. The second page is being displayed with a single link, there is not a post event or something like that.
I guess I should use ViewState but it looks so complicated for this task so please let me know a better way to achieve this.
P.S I'm using C# and Visual Studio 2010
If I understand correctly you have two .aspx pages and you want one page to share information with the other page. Does the first page link to the second page?
I ask because there are a couple of approaches you could take. You could add parameters to a query string in the link to the second page with the information you are trying to send. You could also use the session to temporarily store the information.
For example:
<asp:HyperLink NavigateUrl="www.<yoursite>.com/firstpage.aspx?eggs=1&bacon=yum" Text="Awesome Site" runat="server" />
In the second page you would have this in the codebehind in the Page_Load
string eggs = Request.QueryString["eggs"];
string bacon = Request.QueryString["bacon"];
Now you have the value from page one available in page two.
Another approach might be to use the Session like so:
Page one:
Session["bacon"] = "Yum";
Page two:
string bacon = (string)Session["bacon"];
However, I would advise against overusing session to pass information between pages.
Quick & "Dirty": A session variable which holds the info to pass.
On the first page:
Session["ValueToPassToOtherControl"] = "The value";
On the second page:
var value = Session["ValueToPassToOtherControl"];
Elegant: You need to manage your state in any way (via a static manager whose function is to store and retrieve that info, but that will be also variables). Problem is HTTP is stateless. So you need to bypass this limitation via some kind of storing and retrieving of the data.
You suggested the use of ViewState but forget it, ViewState is the technique used by an ASP.NET Web page to persist changes to the state of a Web Form across postbacks which isn't what's happening on your scenario.
There is a better way that using the QueryString jugglery and Session values.
You could just use the previous page property that is set during cross page posting.
Use an asp link button:
<asp:LinkButton runat="server" id="myLink"
NavigateUrl="~/Page2.aspx"
target="_blank" Text="Go to page 2"></asp:LinkButton>
Then on Page2.aspx.cs:
Get the values from the Page.PreviousPage as follows:
TextBox txtUser = (TextBox)Page.PreviousPage.FindControl("txtUser");
TextBox txtSomeValue = (TextBox)Page.PreviousPage.FindControl("txtSomeValue");
Use these as you require in your second page.
Related
I have two ASPX pages; they use the same DLL and class, so the first line of each file looks like:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="CustomPage.aspx.cs" Inherits="CustomPageCode.CustomPage" %>
(maybe this is bad form to have two *.aspx pages sharing the same codebehind, but I don't want to have two separate classes with identical code)
I'm 'configuring' each page through a hidden field --
Page1.aspx has the line:
<asp:HiddenField ID="DepartmentName" value="DepartmentOne" runat="server" />
and Page2.aspx has the line:
<asp:HiddenField ID="DepartmentName" value="DepartmentTwo" runat="server" />
My CodeBehind reads DepartmentName.Value to do a bunch of codebehind things, like SQL queries, based on the value of the HiddenField specific to each department, and also Javascript reads that value to do department-specific things as well. I'm doing it this way to simplify configuring each page -- the way the page is configured is right there in the ASPX page and the same value is visible to both ASPX and Javascript.
However, if either page does a POST event -- now DepartmentName.Value ONLY returns the value from the page that did the POST for any page with the same codebehind. Page1.ASPX, even though the asp:HiddenField value in the source is still clearly "DepartmentOne", if Page2.ASPX did the POST, DepartmentName.Value will be "DepartmentTwo" regardless of which page is opened.
The funky thing is: if I open the same page in Chrome, Page One will still have Page Two's DepartmentName.Value, even if the POST event never occurred in Chrome; clearing the IE cache doesn't fix it either. This is definitely something happening on the server side, getting cached somewhere. An IIS reset resolves it.
Google has told me that ASP.NET caches a bunch of things from a POST event but doesn't exactly say how it's handled, or how to enable/disable it, or which of the many cache locations it is located in, and many examples look like I'd have to specifically tell it to start caching things in a persistent way. The closest thing I've found is ModelState.Clear(); in a !IsPostBack at the beginning of the Page_Load, but that doesn't resolve it, I'm not using MVC in my code as far as I know.
So, my question is, how do I force that the GET uses the hidden value in the source code, and not some cached value from an old POST event?
It's probably ViewState, but I'd have to see more of your code for this to be more than a wild guess. I do see this:
I don't want to have two separate classes with identical code)
Yep, that's a good thing. But it sounds like maybe you have too much code in the page class itself that should be moved to a separate utility class, where two separate pages can now share that same utility code. Alternatively, you want a single Department.aspx page that takes a URL argument, like this: /Department.aspx?deptid=Department1 or /Department.aspx?deptID=Department2
Then key off of the url argument, rather than a hidden field. If you don't like the ugly URL, you can use routing to get prettier URLs like this: /Departments/Department1 or /Departmennts/Department2
I discovered my problem:
After wrestling with ViewState, it turns out my problem wasn't hidden fields being cached, it was what was being done with the hidden fields.
At the beginning of my class, I have a variable:
public static Dictionary<string, string> ThisDictionary = new Dictionary<string, string>();
that my code uses ThisDictionary.Add() to add values from ASPX hidden fields to -- but I never declared ThisDictionary as 'new' in my actual function, so every time I added an element to the Dictionary of hidden fields, it was persistent across multiple pages using the same class.
So, when I load my values from what I think is the hidden field, the codebehind is reading the hidden field correctly, but when it takes action in C#, it is using the data in the Dictionary with a bunch of other pages' data in it, hence the appearance that hidden field values are being cached somewhere.
By adding a statement to declare it as a new Dictionary<string,string>() at the beginning of my Page_Load function, it now wipes the dictionary clean with each page load and now it's behaving how I would expect, containing only values from the hidden fields on the particular page.
(I acknowledge what I should probably do is have a separate class with these variables in it, rather than lumping it all into the main ASPX class that gets called when the page loads. Something for the next version)
I have a page called webForm1, this page contains a textfield, when a user enters a value, I want the value to show up in a label on webForm2, when I do that, I am getting an error:
Label1 is inaccessible due to its protection level
This is what I am doing in webForm1
webForm2 webform = new webForm2();
webform.Label = textBox1.Text;
Response.redirect("~/webForm2.aspx");
but the above is not working, I am new to programming and not familiar with classes and complicated programming, what is the easiest way to get the value of the textbox in the label?
Thank you.
You can't instantiate the page class (webForm2) in your current page. You'll have to pass the value in another way to the second page and then bind the label. As Jason P says, the ASP.NET framework instantiates the webForm2 page for you, you can't do it yourself.
If the data is not sensitive, use the Query String:
Response.Redirect("~/webForm2.aspx?label=" + textBox1.Text);
This will redirect the user to a page with the url of whatever.com/webForm2.aspx?label=whatevervalue. On the second page, you can pull the text from the query string and bind it to the label:
public void Page_Load(object sender, EventArgs e)
{
Label.Text = Request.QueryString["label"].ToString();
}
Unlike WinForms, you don't instantiate the next form like that. Essentially, your first two lines are incorrect for WebForms. The third line is where you want to focus your attention. You redirect the user to the second form, allowing the framework to take care of instantiating it.
This is because WebForms, despite being "forms", is still an HTTP web application and does everything through requests and responses. By issuing a redirect you are telling the client to abandon the current page and make a new request for the specified page.
There are a number of ways to send a value to this next page. You can store it in some persisted medium (such as a database), you can use session state, etc. Probably the simplest approach at the moment would be to include it on the query string:
Response.Redirect("~/webForm2.aspx?label=" + textBox1.Text);
Then in the next page you'd get the string from:
Request.QueryString["label"]
You may want to URL-encode the text value first, I don't know if Redirect() does that for you. Also keep in mind that this isn't a "secure" transfer of data from one page to the next, because the client has full access to modify values in the URL. So if this is in any way sensitive data then you'll want to look into other approaches. (Keep in mind that "sensitive" could be a relative term... The information itself might not be sensitive but you might be doing system-sensitive things with it on the next page, which we can't know from the code posted.)
So I have a slightly unorthodox application type.
I have an aspx page called AddNewBlog.aspx. This page generates XML data from database queries and it include the file AddNewBlogXSL.aspx which is an xsl style sheet.
The effect is that the AddNewBlog XML data is transformed by AddNewBlogXSL on the client side into XHTML.
So although the requested page is AddNewBlog.aspx, the layouts and controls and forms are on AddNewBlogXSL.aspx since it contains all the layout and formatting.
When on AddNewBlogXSL.aspx I do an asp:button it tries to post back to AddNewBlogXSL.aspx as is understandable.
The problem is that page is an xslt stylesheet not a webpage.. I need it to post back to AddNewBlog.aspx as this is the proper page which includes AddNewBlogXSL.aspx
The only thing I seem to be able to do is allow the default behaviour which is to submit to AddNewBlogXSL.aspx, process the page, and redirect them to the proper page AddNewBlog.aspx but then it makes it hard to handle error messages and such since I have no control over AddNewBlog.aspx after I have simply redirected to it from AddNewBlogXSL.aspx
Any ideas at all?
You are looking for PostBackUrl property.
<asp:button id="Button2"
text="Post value to another page"
postbackurl="~/Path/To/AddNewBlog.aspx"
runat="Server">
</asp:button>
EDIT:
To address your comment, IsPostBack will not be true in this scenario because it isn't a postback, it's just a post to another page. You have to access the values via the Page.PreviousPage property as outlined in the MSDN article I listed.
During a cross-page postback, the contents of the source page's controls are posted to the target page, and the browser executes an HTTP POST operation (not a GET operation). However, in the target page, the IsPostBack property is false immediately after a cross-page post. Although the behavior is that of a POST, the cross-posting is not a postback to the target page. Therefore, IsPostBack is set to false and the target page can go through its first-time code.
Also per MSDN, you would check the PreviousPage.IsCrossPagePostBack property instead of the Page.IsPostBackProperty
if(PreviousPage.IsCrossPagePostBack == true)
{
//Get values from PreviousPage
text = ((TextBox)PreviousPage.FindControl("TextBox1")).Text;
}
Cross Page Posting Details
I went ahead and wrote a little test harness (aka, I took the example off the MSDN page, :-0 )to verify and results are as follows when cross page posting:
It's not an ideal situation and it kludgey to access your values as listed, but for the model you have designed, it's the best I can think of.
In addition to the above answer, Can you please confirm that the "AutoEventWireUp" is false in this page. If so, override the page load method in this case.
I have a webpage 'WPwp1.aspx' and another webpage 'FLcourt.aspx'
In WPwp1.aspx i have DropDownList2,DropDownList3,TextBox1,TextBox2,TextBox3 and a LinkButton1
On click of a link button i want to
redirect to FLcourt.aspx.
FLcourt.aspx also has the controls
that are there in
WPwp1.aspx(DropDownList2,DropDownList3,TextBox1,TextBox2,TextBox3)
When user input value in the controls present in WPwp1.aspx and clicks on LinkButton1, the user should be able to see all the values that were being given as input in 'WPwp1.aspx' into the asp.net controls in 'FLcourt.aspx'.
How is it possible to pass values being input in some controls in a webpage to similar controls in another webpage?
Yes, you have several options:
Use Session variables. This is the less scalable way. Just before Response.Redirect, store
your values in Session and get them in the Page_Load of the target page.
Using QueryString. Pass the values in a query string:
Response.Redirect(
string.Format("FLcourt.aspx?value1={0}&value2={1}",
HttpUtility.UrlEncode(value1),
HttpUtility.UrlEncode(value2)));
And in the second page:
var value1 = Request.QueryString["value1"];
UPDATE
Using cookies (the client's browser must have them enabled). Set cookies before Redirect:
Response.Cookies["MyValues"]["Value1"] = value1;
In the target page:
if(Request.Cookies["MyValues"] != null)
{
var value1 = Request.Cookies["MyValues"]["Value1"];
//...
}
(but you have to check that Request.Cookies["MyValues"] is not null before)
You can try this out.
In your source page ("WPwp1.aspx") create properties for each control i.e. DropDownList2,DropDownList3,TextBox1,TextBox2,TextBox3.
Give "PostBackUrl" property of the linkbutton to the page you want to redirect, in your case it will be "FLcourt.aspx".
In the destination page ("FLcourt.aspx") access the previous page with the help of "PreviousPage" class. This class will give you the properties which you have written in point1.
Hope this helps!
Regards,
Samar
See: http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
To summarize and answer your question directly, you can:
Use a query string.
Get HTTP POST information from the source page.
And since both pages appear to be in the same Web Application, you can also:
Use session state.
Create public properties in the source page and access the property values in the target page.
Get control information in the target page from controls in the source page using the PreviousPage object. This option has a particular performance disadvantage as a call to PreviousPage results in the instantiation of the object and the processing of its life-cycle up to, but not including PreRender.
Sometimes, though, it is simpler to avoid cross-page postbacks and simulate the multiple pages/stages with Panel or MultiView controls.
Use sessions
Use cookies
Use Applications (global)
Post Back URL
Query String
Server.Transfer
Static Variables (global)
http://www.herongyang.com/VBScript/IIS-ASP-Object-Example-Pass-Value-between-Pages.html
its shown how you do it between two pages.
if users press the browser's back button to reach the prior page, the page should display a message like "web page expired".
can i use javascript for this???
for example:
there are 4 pages in web sites. on page 1,2 and 3 the user can use the back-button, wheras on the 4th page the user gets the desired message.
i thought that i can do this by using counter.
i used following javascript on the master page ..
<script type="text/javascript">
function GoBack() {
window.history.go(+1);
}
</script>
and call the function in body like this:
<body onload="GoBack();">
and on the 4th page_load i do the following:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
it is working for all pages .. but i want to do this only for the 4th page
If you only want it on that page level, and when you use postbacks, then I suggest you simply keep it in ViewState instead of Session state. Session's also still available on other pages, where you might want to have other counters.
You need to keep the variable alive across requests. So one way is to put it in some viewstate or sessionstate. Sessionstate is least preferred. But you can possibly put it in a hidden textbox in the page and simply use it.
Looking at the problem after the much awaited update/edit, I shall suggest you to use SessionState. Please give a try on it.