Best way to pass values between web forms ASP.NET - asp.net

What's the best way for passing values between web forms in ASP.NET. I have several web forms linked to a site master and I want that when certain button is pressed in one form , certain information will be passed to another form and the user will be redirected to that form displaying the information retrieved from the previous form.
Ex: Form1 --> click --> go to Form2 --> Display in Form2 the data received from Form1.
For testing it I tried using Session variables but it hasn't worked until now. I declare the variable in the Page_Load of Form1 as following:
Session["diseno"] = "nombre";
but when I go to Form2 I do the following on the Page_Load:
Response.Write( (string) Session["diseno"] )
however nothing is printed. I would appreciate your help :)

Not sure if its the best way for your scenario as its easy to break and not good for secure data you don't want the user to see but I have used URL parameters, They are simple and you can pass multiple parameters.
Source

You could do something like this on your second page and set the variable to a string etc... and use the variable in a label control etc...
string _name = Session["diseno"].ToString();
To just print out your session variable do this:
Response.Write(Session["diseno"].ToString());

Related

How to get the generated Unique ID prefix for a page's controls

As we know, ASP.NET WebForms will generate a Unique ID (as well as name) to a control to prevent collisions in the control heirarchy. Let's say we have a TextBox control with an assigned ID of "MyTextBox" in the markup. If this textbox is on a page with a Master Page then the TextBox control will be given a Unique ID of "ctl00$MainContent$MyTextBox" or something similar.
What I want to know is, for a given page, is it possible to know what the prefix WILL BE? In my above example I would like to know all controls I create on that page will be assigned with a prefix of "ctl00$MainContent$". I have examined the Page object and I cannot find an easy way to extract this information. Note: inspecting already existing controls on the page (like the TextBox) isn't an option. I simply need to know, at run time, what the prefix would be.
-- EDIT: Why do I need to do this? --
Ultimately I am trying to solve the problem that this post illustrates:
ASP.NET 4.5 TryUpdateModel not picking Form values in WebForm using Master-Page
I'm using the ModelBinding features introduced in ASP.NET 4.5. Problem is, as the above post points out, is that the name value collection found in the form will NOT match up with your model's properties. The built-in FormValueProvider expects a one-to-one match with the form key (name) and the model's properties. Unfortuantely, the form's keys will have the typical "ctl00$MainContent$" prefix to the names.
I have a semi-working solution where I created a custom IValueProvider that compares the end of the form key with the model's property. This works 95% of the time, but there's always a chance of multiple hits.
Ideally, and this is what I'm trying to figure out, if I could determine WHAT the prefix is I can then prefix that the IValueProvider's passed in key, look for that in the form and find the exact match.
So that is why I'm wondering if there's any way to know what the prefix should be for a given page.
The real answer is to simply code in such a way that you never have to know this information. that might not always be easy - but that's quite much what we do. You can certainly in code behind get/grab the "id" of the given button.
so for example, I become VERY tired of having to wire up a little toast message all over the place. So, I put in a little js routine (in the master page).
But I did need the client ID of a given control.
Well, the code behind needed (wants) to place the toast message next to whatever I clicked on.
So my server side "toast" message caller of course will after the server side code is done does the common "script" inject that will run when the page finally makes it final trip back down to the browser, displays the page, and then of course runs that script I injected.
So, my server side code does this:
MyToast2(Me, btnUpdate.ClientID.ToString, "Update ok!", "Settings changed")
So note how I get/grab/pass the "ID" of the control that the server is going to render. You can use ClientID to get the the final "ID" used for that control in code behind.
So, that btnUpdate is just a simple button placed on the web form. But who cares what super ugly "ID" the server assigns. i just need the "id" of the control so the JavaScript client side can pick up that control - and thus know/get/have the position of the control, and thus I get this result:
Or if I am some place else - again I can call that js routine - and that routine needs the current control. so might have this:
So, I can now just call a routine and pop up a message - not have to write any new js code for the gallzion notices and little pops I have all over the place.
so the little javaScript routine of course does this:
function toastcallm(cntrol, h, t, d) {
var cmd = $('#' + cntrol);
var mypos = cmd.position();
bla bla bla
But only important was that I get/determine and pass the used server "client" id to that routine - I don't really care what it is , or how to see, or how to list them out. I suppose a better jQuery selector or using wild card might work - but I really don't want to know the control ahead of time - but only that I can get the clientID used when I need it.
I simply write code that assumes somewhere along the way when I need such a client id, I simply get it and use it.
So, on the server side? Well, we always build and write code based on the control ID, but you want to get your hands on the actual id? Then you can use in the server code behind:
btnUpdate.ClientID.ToString
(ie: somecontrol.ClientID).

How to pass parameters from one page to a report viewer in another page

I am trying to generate a report by passing parameters selected using two drop down menus which are in page1.aspx and sending them to page2.aspx which is the page for my report viewer (and the report i want to generate).
I tried to use the response.redirect command and server.transfer command with the help of click_button event from my code behind page for page1.aspx but it didn't work.
Can any body help me how to do this, i am trying to figure this out since a really long time and i am new to ASP.NET, i also tried to google it but couldn't find any information regarding the same. Any help would be really appreciated. Thank you
I repeat the question:
What is the way to transfer parameters from page1.aspx to a report viewer in page2.aspx such that the parameters are selected using two dropdown menus in page1.aspx and are used as a criteria to generate report in page2.aspx?
You could create an object class where you save the state of parameters.
Inside that object you create 2 variables par1 and par2.
In page1.aspx when you define what the parameters are, assuming this is not directly a report parameter, but still has to be passed into a report that you will load, you could create a new instance of the class object, store the variables within, and reference that object in page2.aspx when calling the report url into the reportviewer.
In case you are loading parameters inside the report, i think you need a dataset in report1 that uses a stored procedure that includes saving the parameters in a database table. That way, in your second report you can call for this stored data directly in the database.
Those 2 solutions i think should do. If you need more help let me know.

pass a value into next page

I have login page, once logged in I create a session variable to store the UserName.
I've used this variable to retrieve info for this User from Account table with AccountID, name etc and I return the AccountID on the page using a label (lblAccountID).
I have a button to "Add Funds" to this account, which redirects to the AddFunds.aspx page
How can I pass the AccountID into the AddFunds.aspx page which will be used to insert details into Funds table which has the AccountID.
I don't want the AccountID to be visible on the AddFunds.aspx page.
there are multiple ways to achieve this. i can explain you in brief about the 4 types which we use in our daily programming life cycle.
Please go through the below points.
1 Query String.
FirstForm.aspx.cs
Response.Redirect(“SecondForm.aspx?Parameter=” + TextBox1.Text);
SecondForm.aspx.cs
TextBox1.Text = Request. QueryString["Parameter"].ToString();
This is the most reliable way when you are passing integer kind of value or other short parameters.More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:
FirstForm.aspx.cs
Response.Redirect(“SecondForm.aspx?Parameter=” + Server.UrlEncode(TextBox1.Text));
SecondForm.aspx.cs
TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());
2. Passing value through context object
Passing value through context object is another widely used method.
FirstForm.aspx.cs
TextBox1.Text = this.Context.Items["Parameter"].ToString();
SecondForm.aspx.cs
this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer(“SecondForm.aspx”, true);
Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.
3. Posting form to another page instead of PostBack
Third method of passing value by posting page to another form. Here is the example of that:
FirstForm.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
buttonSubmit.Attributes.Add(“onclick”, “return PostPage();”);
}
And we create a javascript function to post the form.
SecondForm.aspx.cs
function PostPage()
{
document.Form1.action = “SecondForm.aspx”;
document.Form1.method = “POST”;
document.Form1.submit();
}
TextBox1.Text = Request.Form["TextBox1"].ToString();
Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false
4. Another method is by adding PostBackURL property of control for cross page post back
In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.
FirstForm.aspx.cs
<asp:Button id=buttonPassValue style=”Z-INDEX: 102″ runat=”server” Text=”Button” PostBackUrl=”~/SecondForm.aspx”></asp:Button>
SecondForm.aspx.cs
TextBox1.Text = Request.Form["TextBox1"].ToString();
In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.
You can also use PreviousPage class to access controls of previous page instead of using classic Request object.
SecondForm.aspx
TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1″);
TextBox1.Text = textBoxTemp.Text;
As you have noticed, this is also a simple and clean implementation of passing value between pages.
Reference: "How to: Pass Values Between ASP.NET Web Pages"
You need to store it in a session variable:
int AccountIdVar;
Session["AccountID"] = AccountIdVar;
then you can retrieve later by
int AccountIdVar = (int)Session["AccountID"];
You can either use the session variable you stored in the previous page as it should still be accessible or another way is to pass the id over via a querystring such as www.foofoofoo.com?Id=23456.
As the others said, you can use Session or Querystring values. You can also just POST to the new page
The How To Pass Values Between Pages page is worth looking at too.
The MSDN article about Pass Values Between ASP.NET Web Pages is the best place to look for.
For this we can also use Global variable, create a module class in that declare all variables with public data type, then assign the values. Once the value is assigned it can be accessed from anywhere.

Retain Dynamic dropdown values

I have 3 dyanmically generated dropdowns in this aspx page. The 2nd and 3rd one are populated as per the selected value of the first one (I've the code for creating the 2nd and 3rd dropdown in 1st one's selectedindexchanged event)
How do I write the code in a such a way that when I traverse back to the page, the dynamic dropdowns retain their selected values?
I'm assuming that what you mean when you say that you "traverse back" to the page is that you navigate to a different page on the site and come back to this page that it's dropdown values will be filled in with what the user selected.
Remember that HTTP is an inherintly statless protocol in that it won't remember data in between postback to the servers. In order to overcome this limitation ASP.NET and other web frameworks use various ways of saving data between request. Currently you are relying on "ViewState" that is stored within the page as a hidden variable called __VIEWSTATE (look at the page source sometime to get an idea of what field looks like) this scope of this hidden variable is when the page first gets loaded and everytime you do a postback to the same page. From your description you probably need a longer term persistance called SessionState or Cookies that will store values for a particular Session.
Here is a link from MSDN that contains interesting information regarding all the possible ways of saving state in an ASP.NET application. Let me know if you've got any other questions.
http://msdn.microsoft.com/en-us/library/75x4ha6s.aspx
--EDIT--
Here's a link to the MSDN article on Session State. My recommendation is to be careful with Session state and only store things that are absolutely required. Also I'd recommend you have a Class that contains the a bunch of constant for the Session Keys. It's easier to manage
http://msdn.microsoft.com/en-us/library/ms178581.aspx
ie instead of
string value = Session["Key"];
//Create a class SessionKeys
Class SessionKeys{
public const string SESSION_KEY = "Key"
}
//Now that string is strongly typed and you don't have to worry about misspelling it
string value = Sesssion[SessionKeys.SESSION_KEY];

Given a user control with a form containing validation can I validate entirely server side?

We have an existing User Control that was built to dynamically generate a web form for an end user. This form includes required field validators, custom validators that use server side code and Regular Expression validatiors.
We now have a need to use all these validators to verify that all the needed data is entered when using a separate ordering process that cannot be validated in the same way, but has the same validation requirements before it is added to the database.
I would like to use this user control to validate the input by passing it all the values and checking the validation summary. The only way I know how to do this is to render it to a page on the client side and trigger the form submit.
Is there any way to populate and validate a web form entirely on the server side?
It is definitely possible to create an instance of an .aspx page and invoke it on the fly, although it can be fraught with complications depending on what you are doing. Here's the basic idea:
Page instance = BuildManager.CreateInstanceFromVirtualPath(
"/myPath/myPage.aspx",
typeof(MyPageCodeBehindType)) as Page;
Presumably now you can call instance.ProcessRequest(HttpContext.Current) on it and have it go through the Page lifecycle. Again presumably you can check instance.IsValid and see if your Validators worked or not.
I say presumably because I have very little experience with this. Give it a shot - maybe check out the BuildManager class for some more examples.
EDIT: Looks like you can do this:
UserControl instance = (UserControl)BuildManager.CreateInstanceFromVirtualPath(
"~/Controls/Somefile.ascx", typeof(UserControl));
Yes, have you looked into LoadControl?
Dim dp As missico_UserControls_DropDownListDeviceProfile = LoadControl("~/missico/UserControls/DropDownListDeviceProfile.ascx")
'Dim dp As missico_UserControls_ComboDeviceProfile = LoadControl("~/missico/UserControls/ComboDeviceProfile.ascx")
Dim DeviceID As Integer
Dim MarketID As Integer = 0
DeviceID = dr("DeviceID").ToString
dp.SelectedValue = ProfileID
dp.DeviceID = DeviceID
dp.ID = "d" & DeviceID & "m" & MarketID
dp.OnClientChange = "pc(this);"
dp.ShowLabel(CBool(gscID = 1))
LoadControl should work for you. Yet, if the user control is not designed for true standalone operation, you could create a page that wraps the user control. Do a server transfer to the page. Have the page populate the user control, validate it, process the output, then transfer to an acknowledgement/error/original page.
I have used both these techniques, but can't find the server transfer code right now.
Not sure. It may be possible to create an instance of your user control's class, populate its fields by setting the .Text fields for each of its controls, call .Validate() on it, and check its isValid() value.
If that doesn't work, you may be better off designing separate validation for the "separate ordering process", if it is feasible. Can you give more details on how that is implemented?

Resources