How to preserve viewstate of textbox on postback when ajax is used ? - c#

I have created the webpage default.aspx inherited from Master page. I have used ajax update panel on default.aspx.
There are 3 textboxes on default page. When I click on submit, the error occured on the page and there is link Show Error which redirects to showError.aspx which shows the error details.
On showError.aspx page there is back button which onclick return back to default.aspx. In this process it looses the viewstate of textboxes at default page.
So how can I preserve the viewstate when ajax is used ?

this is typical behavior for webforms. viewstate is valid between postbacks. meaning you are posting to the same page(url). if you leave that page and go to another, then you are abandoning viewstate. the next time you return to that page viewstate is reset. the server doesn't know how you got the page (address bar, html button/link, or using history). it just knows you did arrive.
the short answer is you don't preserve viewstate. doing so defeats the purpose of viewstate. it's only meant to exist between postbacks. There are ways to preserve the user input, but this may require conceptual and design changes to how you are managing the validate and errors.
for example.
1. validate the user input (required, range, regex, etc.
2. validate the business rules (customer is valid, date is after point in time, customer's account is not on hold, etc)
3. process the request.
1 & 2 should catch most problems and return the user to the same page, with fields populated and a list of errors why the request was not successful.
If an error occurs at #3 then it's truly exceptional and should abandon all work. the user shouldn't return to the previous page with state preserved because something really is wrong that you were not expecting.
and all of this is indifferent of what the input is and whether or not you use ajax.

Related

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 ;-)

ASP.NET Dynamic user controls save data issue

Here is what I have
A set of business entities that resides in the session (for example, Employee:{"Name":string,"Surname":string,"Salary":double, "Position":enum}
A set of user controls (using Telerik.Web.UI), each of it describing a business entity (for example, EmployeeControl.ascx:
RadTextBoxes for Name, Surname and Salary and a RadComboBox for Position. There is also a RadButton in the control, which saves the data that is entered in the controls client-side to a certain entity, which is already known by the time the control is loaded).
A page with a RadTabStrip and RadMultiPage, which is used to render different controls in different tabs
The target RadTab that hosts our Employee control.
So, the issue is: when I hit the Save button, a postback is done, thus clearing my controls and only after that the Click event is fired. I have tried to avoid it by using RadAjaxManager with a OnClientClicking script with canceling the postback, but with no success, because a postback is still generated, although its __EVENTTARGET is RadAjaxManager itself.
Basically, this is what happens:
The user selects a tab with the Employee control with it. The control is filled with initial data on Page_Load. (A postback occurs with re-creating my controls)
The user modifies the data. (Nothing happens, no control generates postback)
The user clicks save. (A postback occurs with re-creating my controls, then a Click event is fired)
No data is saved
When the data is entered again and the save is called, everything is saved as it should.
How can I make this work correctly?
P.S. I was able to achieve the required result (although not completely: the screen "flickers" when a postback is done) by dividing the postbacks into odd ones and even ones (I added another variable in Session named PostCounter, which is incremented every time the page is posted). So, when an expression PostCounter % 2 is equal to 0, I perform another postback by executing __doPostback with its eventTarget parameter being the ClientID of an instance of a RadAjaxManagerProxy, and the argument being just some string that does not match any that is used in my regular Ajax requests.
Make sure your controls always have the same IDs when recreated. Imitating postbacks from other controls should not be needed, the buttons are IPostBack controls so things should work nicely.
This (one AJAX, one full postback) behavior is typical for Sharepoint where you need to add AJAX settings programmatically: http://www.telerik.com/forums/radajaxmanager-in-webpart-on-sharepoint-2010
Also, make sure you do not nest AJAX settings (from a manager and/or proxy), RadAjaxPanels and asp:UpdatePanels: http://www.telerik.com/help/aspnet-ajax/ajax-controls-in-ajaxpanel-and-ajaxsettings.html.

EnableViewState = false - - but still seems to be "working"

I'm a new C# programmer and have just created a simple program. I first wanted it to count button clicks, maintaining the cumulative count across clicks (post backs). This worked.
Now I want to turn off EnableViewState and see that the clicks do NOT accumulate. So I turned off EnableViewState (EnableViewState="False") for the text box (named txtCount), but somehow it still keeps counting and accumulating my clicks across posts. Am I missing something here? How can it be maintaining the state of this text box without ViewState on?
protected void Button1_Click(Object sender, EventArgs e)
{
int count = int.Parse(txtCount.Text);
count++;
txtCount.Text = count.ToString();
}
You're not using ViewState, you're using the form element itself. Here you read from the form element:
int count = int.Parse(txtCount.Text);
And here you write back to the form element:
txtCount.Text = count.ToString();
So the value is being stored in the input that's emitted to the HTML, and posted back as part of the HTTP form post.
If you want to examine this more closely, take a look at your browser's debugging tools. (FireBug, Chrome developer tools, IE developer tools, etc.) Look for the tab/panel/etc. where the network activity is captured. When you click your button, you'll want to watch the POST request that's being sent to the server.
Within that POST request is a series of key/value pairs. Every active form element on the page sends a key/value pair, and the entire viewstate is itself just a key/value pair from a hidden form element. (Where the value is a base-64 encoded string.) If the form element has the value in question, it's in the POST request and, thus, available server-side.
Remove the text from the text box between posts and it should stop counting. (Probably even throw an exception on int.Parse().
Both really good answers above. A good way to remember it (and to realize why ViewState is required at all) is that standard HTML form elements (such as asp:TextBox which renders as an HTML input) will be included in the POST, whereas non-standard HTML form elements (such as asp:Label which renders as an HTML span) won't be so you have to use them with ViewState.
Try switching your asp:TextBox to an asp:Label. You'll see that it breaks when you turn off ViewState, but it works with ViewState on. This is because HTML span values are not included in HTML form posts.
This is a pretty good article that discusses ViewState, even though it's pretty old: http://msdn.microsoft.com/en-us/library/ms972976.aspx
You are misunderstanding the difference between post back data (Form) and ViewState.
ViewState is actually a hidden field with encoded data that is used by ASP.NET to reconstruct certain parts of the page on postback, which is why you think you need it to be turned on for your text box example to work.
While you did not show your markup, I will pretend that this is what you have:
<asp:TextBox id="txtCount" runat="server" text="Enter a number here" />
Now the user types in a number at run-time (say 7 for argument's sake) and posts the page back to the server.
The server receives two pieces of data, the post back data (7) via the Form and ViewState, which is the hidden field.
In your example, the ViewState from the text box's point of view, contains the data Enter a number here, while the Form contains the value the user actually typed into the text box.
Note: As an aside, if you look into ASP.NET MVC you will find that ViewState does not even exist. After learning some of the ASP.NET WebForms constructs, I recommend you read Compatibility of ASP.NET Web Forms and ASP.NET MVC.

Go back to to previous page ASP.NET

Im having an issue of going back to the previous page. The page i want to go back to had a few radio buttons which you had to select, after this you went to the next page which is the current page which then you can select certain things BUT I want to be able to go back to the previous page and the original selections for that page still be selected.
Anyway i could do this if so how?????
You can do a real basic back button with the help of JavaScript.
window.history.go(-1);
which will take you back to the previous page.
By default in ASP.NET state of controls is stored in ViewState, so it should be the same as user left them.
It is probably some view-state issue.
Go to your codebehind and check PageLoad method. If you are creating or setting radios in PageLoad, you do not want to re-init them every post-back.
if (!IsPostBack){
// your init here
}

Passing data between Views and Controller

Wanted to see if somebody can provide some suggestions/pointers on how to address this issue I am currently facing
.
Scenario is likeā€¦
I have a Page say A where search is performed and data is displayed.
On Page A there is an ActionLink which passes an ID of the selected record to the page B.
Before redirecting to page B, I need to store/preserve form data of Page A (I do not want to use session or hidden filed as data is critical).
Once user is done working on Page B, I need to save changes on Page B and redirect back to Page A.
Here Page A should make a Post request based on preserver form data in step 3. Purpose is to display back searched data that was there before redirecting to Page B.
Something like..
View A
// Search textboxes here
// Search data list here with ActionLink column
View B
// more controls here
// Submit button - saves changes on this page.
// after submit button processing need to go back to View A
// and display the same Search data List based on Seach textboxes values
// those were entered by user before coming to this View B.
// Ques: Not sure how to persist data from View A between calls to View B and then View B to View A.
Does anybody has any better approach to achieve this?
For now the solution I have is...
Make an ajax POST request on ActionLink click and save the
formcollection in cache using controller.
Make default ActionLink GET request passing ID and in controller
return View B.
On View B, on submit do ajax POST request to save data on Page B and
return data from cache in ajax success function.
Make another ajax POST request using data retruned in above ajax
success to display View A.
Thanks in advance
If you're relying on full page refreshes then you need to use Session. You didn't give a reason as to why you don't want to use it, but Cache object is totally inappropriate for this purpose as it can be cleared out if the server needs to regain some memory, as well it is shared between users. Session is specifically built for the purpose you're describing - preserving data between full page refreshes.
Alternatively I would look into building your site as a Single Page Application, aka, you don't do full page refreshes between navigation, and can store data in a javascript object on the client. Due to the fact you put a lot of emphasis that the data is critical, the Session might be safer though as your javascript objects will get cleared out if the user accidentally navigates away from the page, where is a server based session object will preserve it for the duration of the session lifecycle.
You can also store the data in a cookie/local storage object (html5), but this is probably overkill for what you're doing.

Categories