When do I need to use ViewState - c#

I am confused in how to use ViewState in C#, for example what is the benefit of using:
ViewState["VST"]="Value1";
Lable1.Text= ViewState["VST"].ToString();
Whereas I can use:
string container= "Value1";
Lable1.Text= container;

Your ViewState consists of variables that are kept with the post-backs of your page, because they are sent to the client and the client sends them back with the entire page.
Hence, if you do:
string container= "Value1";
Lable1.Text= container;
Then the users sees the page and hits the submit button, your container string will not exist.
If however you uses the ViewState, ViewState["VST"] will still have the value as it will be "refreshed" when the user submits and sends the page back.
Read more here and also understand the ASP.NET page life cycle.

As per documentation:
View state is used automatically by the ASP.NET page framework to persist information that must be preserved between postbacks. This information includes any non-default values of controls.
You can also use view state to store application data that is specific to a page.
For details see a link:http://msdn.microsoft.com/en-us/library/bb386448(v=vs.100).aspx

If you want to persist the values after postback also than ViewState is the best option.

Every time your application do postbacks current values of your controls are being wiped out. So in order for you to store any values WITHIN THE PAGE you can save them in ViewState. Of course you must set the EnableViewState property first to true. Additional info, if you want to store any value or state while jumping into multiple pages you can use Session instead.

Related

How to maintain a counter variable thats value can be used in Page Init

This subject seems to be be beaten to death and yet I still can't find an answer.
I am trying to allow users to click a button to add a usercontrol to a page. Hypothetically, they can do this as many times as they want. I know I need to recreate these controls on Postback, and am trying to do this in Page Init so that viewstate can give them back their values in page load.
My problem is I have no idea how to keep a running counter that I can use in Init to recreate the proper number of controls the user has put on the page. Viewstate is not available in Init so I can't just use a hidden field where I could increment or decrement the value. I also cannot use Session variables. I am not allowed to use them in this particular project.
As an FYI, I'm adding and deleting these usercontrols successfully right now when I do it on Page Load. But, the fields within the usercontrol do not retain their values consistently between postbacks.
You can always keep this count in the client, and add it to the URL for instance.

Keep Value of Hidden Filed in Master Page

I have a hidden filed in my master page and there are several pages using this master page.
in first page I will change the hidden filed value and it works fine, but when I change the page that hidden filed will be reset. How can I keep its value on page changing?
There are several ways to go about this, you could use cookies, or (how I would do it), you could store that value in a session object instead then you can access it anywhere in your application.
But if you want to keep using a hidden field in a Master Page, this has been answered several times here before.
Here's a good example.
https://stackoverflow.com/a/10348525/3299157
and here is an example showing how to use session objects:
https://stackoverflow.com/a/5282694/3299157

Not getting hiddenfield value after coming back from another page

I have two pages called test1.aspx and test2.aspx.
In the test1.aspx there are some hidden fields.
I am first storing some value to all hidden fields and redirecting to another page called test2.aspx. when I am coming back to test1.aspx, I am losing the values of hidden fields.
How can i make the values of hidden field as it is even after coming back from another page. I can't use session or any other server side state management techniques.
Are you using Server.Transfer or Reponse.Redirect to navigate to the next page?
Reponse.Redirect destroys the history of the current page in the web server, while Server.Transfer keep the history.
Try: Server.Transfer("test1.aspx")
Enjoy ;-)

Saving data on a web page when switching from one page to another in ASP.NET?

I'm new to ASP.NET. I'm designing a user interface in Asp.NET and C# where the user can login and then launch an application. When using this application the user has to fill out a form that is 10 pages long.
So, I have used navigation menu and designed the interface in such a way where every page is different menu item and it is a static menu. The user fills out the details on the first page of the form and saves it and the data gets saved in the database.
The problem is he moves to the other page by clicking the menu tab; when he comes back to the first page by using the menu tab for that page all the filled in data is gone and he sees a blank page. I know that is how it works but I want it in such a way that in one sitting when he is filling out the data on the second page (after filling the data on first page) on reverting back to the first page he should be able to see the data that he had filled out.
What concept can I use? I'm not sure view state will be helpful in this scenario.
You should look into using the Session State variable for storing his information over the entire session. If the user is logged in you should think about storing his information that he enters in a database and having a Boolean state of "ApplicationFinished" to check if he has finished it or not. Otherwise I would have a call on each page to retrieve information from the database that has already been added, so that he can fill out information at different sittings or all at once.
http://msdn.microsoft.com/en-us/library/ms178581.aspx
Session State may be too long term for you, and if that is the case do some research on ViewState. There are a lot of different ways to tackle a problem like this. It all depends on which technology will fit your needs the best.
http://msdn.microsoft.com/en-us/library/ms972976.aspx
Also, if you're using a tab system think about using the AJAX tabs so that the data will remain on the forms even while tabbing through the different tabs.
http://www.dynamicdrive.com/dynamicindex17/ajaxtabscontent/
Well, if you are write the data on database, i guess the best (fast) workaround is to add a column named "completed" to the table the hold this informations. If the flag "completed" is not setted to 1, you load the database information and fills the page controls.
When you create a new record in the database, get the ID of the record and set it on Session. If the user gets back to the first page (previous page), you can recover the information ID and load the data.
As long as you are learning new things... add jquery to the list and leverage the JQuery Wizard Plug In. It will allow you to integrate your "10 page form" into a single unit, which can then be sub divided, routed and managed more easily. You can leverage AJAX to save each step, while offering built in navigation and validation methods.
I would suggest that you switch to using client-side javascript to control your tabs. That way your form data stays in the fields when you switch back and forth between tabs. You can use javascript buttons to guide the user from tab to tab.
I've done this using JQuery. I actually had 150 fields that needed to be captured (they were all required). I group like data on different tabs and then had buttons ('< Previous', 'Next >') which would activate different tabs.
When they are done, then display the 'Save' button.
This not be what you are looking for, but if your problem is that you want all of the input of a previously filled page to show up when a user navigates back to it, and you have already saved all that information, then you can try something like this:
HTML
<input type="text" id="yourID" name = "yourName" value = "<%=data%>"/>
Then all you need to do is set data to public in the code behind. Then to get the value for data just make a call to your database.
Make sure that you make data empty on the init call public string data = ""; or whatever type it is. This way if there is no info, then it will be blank, and if there is saved info, then it will be filled in.
You can also attempt to pass all the data through params in the url like so:
C#
Response.Redirect("webpage.aspx?data=" + data + "&data1=" + data1);
Or though javascript:
window.location = ("webpage.aspx?data=" + data + "&data1=" + data1);
To get the request do this:
if (Request.Params.AllKeys.Contains("data"))
{
data = Request.Params["data"];
}
This way is less ideal though if there is a lot of data being passed.

Passing values and saving values temporarily, ... use session, hidden field, query string or other?

This may be a basic question... However I've just been picking a solution without giving much though to it...
Consider a page with a grid of forms: /FormList.aspx
where choosing to edit a form redirects the user to a page like: /FormEdit.aspx?Id=2
I usually am okay with passing the values in the query string, because I check in the code-behind of FormEdit that the Id is valid. Which is the best way to pass the value, though: session or query string? Or other?
While the user is editing the form... I usually save the Id temporarily in session (to avoid getting it from the url again). During the user's form edition, what is the best way to store the value? In the session or in a hidden field ? Or other? (When I want to store a temporary DataTable, I believe I can only use the session, but when it's an integer value...)
Thanks in advance for your suggestions :)
I would suggest not to use Session for something that can easily and quickly be stored and checked in a query string or hidden form field; the information you seem to be talking about here is perfect for the query string.
Note that Session could introduce bugs when someone attempts to edit multiple forms at once in different tabs. When they save one, the Session value taken would be from the last one they loaded up to save... likely not what you will want, and it would likely be difficult to figure this out.
What you should do is persist the formID in the query string/form fields, and just double-check it for sanity when they submit the save; Make sure it's an ID that exists and that they are allowed to edit, for example.
Normally QueryString is a good choice if you are having very small data to trasfer between your pages.
2- Session would be a great when you want to store user specific data.
in you case , best would be the querystring as you are sending very small data (ID ) to the next page.
A few things to consider:
If manipulation of the value is a security risk you need to either save it on the server side, or secure the value client side(Which isn't easy to get correct). Or even better: recalulate them.
Saving in the session can easily create problems if the user has the website open in several tabs at the same time. It can also break the back button.
For example if you safe the ID of the item the user is currently editing in the session, and the user edits two entries at the same time the content of the one he started editing first might be written into the entry he started editing later.
My suggestion is to keep the value in a session variable, but when you run the page_load of FormEdit.aspx for first time, save the value in the ViewState of the page, and clear the session var.
Something like that (in page_load of FormEdit.aspx):
if (!IsPostBack)
{
ViewState["MyVar"] = Session["MyVar"];
Session.Remove("MyVar");
}
The problem with ASP.NET and query strings is that they persist on postbacks. That is, the form action for any page defaults to the url including the query string that was used to load it.
If the ID in question is just used to choose a particular form (and is not related to user data) this is not a big deal, in fact it's probably what you want.
On the other hand, if it identifies a record, you may not want this. Assuming you code things properly, this should not present a security risk, but it can give the user the impression that there is one by exposing the internal ID of a record in the query string. It also just looks unfortunate.
There are ways to work around this, and I think in 3.5 you can programatically change the form action. (It used to be you had to use javascript to do that - even though the form action was exposed it could not be changed).
The best way to deal with this is avoid query strings for any data record identifiers. Use POSTs to load data records instead, e.g. instead of using an asp:HyperLink control, use an asp:LinkButton control.
Of course, since POSTS load the same page they are sourced from, this requires that your forms be on the same page as your list. So, instead of having two separate pages, FormList.aspx and FormEdit.aspx, just put the code on the same page so you can post back directly. Presumably each of your forms is in a UserControl anyway. So your main page just has the job of choosing which usercontrol to show, everything else is delegated to the user controls, and all the parameter-passing can be done through posts inside your main page. This is a better architecture and keeps everything nice and clean.

Categories