Keep ASP.NET Multiview in current ActiveViewIndex - c#

In my ASP.NET Web Forms, I have a MultiView that, when it is on ActiveViewIndex 2, will always go back to ActiveViewIndex 0 when a postback is done. When I insert/update a row in the database, I need it to show on the current ActiveViewIndex after it submits to the database. How do I keep it on the current ActiveViewIndex after the web form submits? Maybe this can be done using ViewState but I have never used it before so I wouldn't know how.

For storing per-page data you can use ViewState, or have hidden input field which will preserve data after each post-back.
Viewstate is like a dictionary: when view 2 is displayed store that to viewstate (ViewState["activeTab"] = 2;), and on page load check if there's some value in viewstate, and change active view index if it is:
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["activeIndex"] != null)
multiView.ActiveViewIndex = (int) ViewState["activeIndex"];
}

Related

Page Refresh Causing Postback - Asp.net

I have a form inside a Usercontrol, & calling this from a page say index.aspx.
After submitting the form and clicking refresh, it again causes postback.
So, I tried to maintain a flag in a viewstate as '1' after data saved and '0' when it is initial page load.
But why does the viewstate change its value to 0 with refresh.
How to resolve this.
MyForm.ascx.cs
protected void Page_Load(object sender, EventArgs e){
if(!IsPostBack){
ViewState["DataSaved"] = 0;
}
}
protected void btnSubmit_Click(object sender, EventArgs e){
if (Page.IsValid && Convert.ToInt32(ViewState["DataSaved"]) == 0){
//save data;
ViewState["DataSaved"] = 1;
} else{
ViewState["DataSaved"] = 0;
}
}
On refresh the page is reverted as it was initially (you came to this page via GET request).
So Viewstate is returned to its initial state and all changes made to it are lost. This is normal behavior. The behavior you expect is more like a session, so you might try using a session - it will maintain its state between requests.
Look at this for general understanding of page life cycle in .net:
http://msdn.microsoft.com/en-us/library/vstudio/ms178472%28v=vs.100%29.aspx
And this for explanation of Viewstate:
http://msdn.microsoft.com/en-us/library/ms972976.aspx
Both will be very helpful for you!
Good luck.
To make it simple, ViewState is saving inside user machine, and Session is saving inside server machine (access by cookies).
ViewState will be refresh whenever page IsPostBack or !IsPostBack
Session, however, will not.
In your case, i think you should use Session, instead of ViewState.
To understand more, you can go through ASP.NET Life Cycle. It's always good to learn from basic
Use a Session instead of the ViewState.

How to properly use a QueryString in .NET ASP C#?

I have a web form in .NET using ASP and C#. This form has a DropDownList control with its AutoPostBack property set to True.
Some data on the form is displayed when the user selects an item from the DropDownList.
Now, I want the user to be able to share his or her data by just copying the URL which has the QueryString on it like http://www.site.com?ProdID=1234.
I have done the following to try to accomplish this:
protected void Page_Load(object sender, EventArgs e)
{
// check if the URL has a QueryString item if yes the use it.
if (!String.IsNullOrEmpty(Request.QueryString["ProdID"]))
{
ddlProduct.SelectedIndex = ddlProduct.Items.IndexOf(ddlProduct.Items.FindByValue(Request.QueryString["ProdID"]));
}
}
The Problem with this code is that when the user chooses a different item from the DropDownList his or her selected item gets overwritten by the Page_Load() since we have now a QueryString on the URL. (I build the QueryString and then use the Redirect() method to the same page on an Event)
So my question here is: Is it possible to keep changing the URL's query string on the fly when the user changes the selected item from the DropDownList and display the proper data on the form for the selected item?
I have the feeling that this is like the chicken or the egg problem.
Thank you.
Check for whether or not the page is posting back to the server, along with your existing logic, like this:
if(!IsPostBack && !String.IsNullOrEmpty(Request.QueryString["ProdID"]))
{
ddlProduct.SelectedIndex = ddlProduct.Items.IndexOf(ddlProduct.Items.FindByValue(Request.QueryString["ProdID"]));
}

Event before redirect to another page

I've just developed a new GridView MultiFilter control ( CompositeControl ) that works like the image below:
I use ViewState for my control's properties so it keeps all values after postback. I want to save my control properties to a Session before redirect so I can load properties back to my control when my page loads again.
Does anyone have any suggestions about how this can be accomplished?
You have to do 2 things in this list page:
(1)Page load
(2)Search click
And 1 thing in detail (redirected) page:
(3)Pass some query string while back to list page
(1)while page load decide to load normal or searched (back from detail page) data
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["back"] != null)
bindDataFirst();
// same data load logic as present
else
bindDataForBack();
// you come back from detail page hence bind search & grid data
}
private void bindDataForBack()
{
strName = Session["SearchName"] == null ? "" : Session["SearchName"].ToString();
// check session search conditions & data and bind
//also bind grid by respective search parameters & search options (top side)
(2)search click store search data into session
public void btnSearch_Click(object sender, System.EventArgs e)
{
Session["SearchName"] = strName;// store search data into session variables
//bind grid by respective search parameters
(3)in redirected (detail) page set back button like:
public void btnBack_Click(object sender, System.EventArgs e)
{
Response.Redirect("ListPage.aspx?back=1");
I hope this may helps you. I suggest to implement this with one textbox & grid and then try with your present scenario.
Please mark this answer useful if this solve your problem.
You can assign data to Session the pretty much the same way you assign to ViewState.
It's a key value dictionary just like ViewState.
Ex:
Session["someKey"] = "An arbitrary value";
If you can redirect to another page using form submit then You can post your form to the required page using action attribute of your page. This way values of all controls will be available in the Request["KEY NAME HERE"]
<form action="anotherpage.aspx" id="frmData">
<!-- YOUR CONTROLS HERE -->
<input type="submit" value="Submit" />
</fomr>
you can also submit your form using JS
$("#frmData").submit();

viewstate disappears on response.redirect

On my asp.net c# page I have two text boxes(start and end dates) with ajax CalendarExtenders. The user selects a start date and then an end date. On selecting the end date, I bind my grid as shown below;
protected void calEndDate_TextChanged(object sender, EventArgs e)
{
BindGrid();
}
In the grid I have a command button with the following code
protected void gvAllRoomStatus_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Manage")
{
GridViewRow row = gvAllRoomStatus.Rows[Convert.ToInt16(e.CommandArgument)];
int BookingID = Convert.ToInt32(row.Cells[1].Text);
DataClassesDataContext context = new DataClassesDataContext();
Session["BookingID"] = BookingID;
Response.Redirect("CheckIn.aspx");
}
}
When the user goes to that page and clicks the back button all the selected dates and the gridview data disappears. Any ideas why the viewstate is disappearing?
ViewState belongs to the current Page.
Have a look: http://www.codeproject.com/Articles/37753/Access-ViewState-Across-Pages
Yes, we can access the viewstate variables across pages. This is only
possible if Cross Page Posting or Server.transfer is used to redirect
the user to other page. If Response.redirect is used, then ViewState
cannot be accessed across pages.
So you could use Server.Transfer instead or use the Session.
Viewstate to look at it in a very simplified way is to see it as a carbon copy or cache of the last state of the page you are currently on. Therefore doing a redirect to any page, even the same page itself, is essentially a fresh start. The viewstate no longer applies as for all intent and purpose, you are on a new page.
As Tim suggests in his post, either store the required data as a session variable or use a server.transfer.
Take a look here for a nice overview of viewstate:
http://www.codeproject.com/Articles/37753/Access-ViewState-Across-Pages
In my opinion the issue you have is because you make auto post backs with calEndDate_TextChanged using Ajax.
After your submit, when you press the back button the browser can not remember neither can save what you have change with all that auto post data with Ajax calls, and you lose them.
For me remove the Text Change auto post back, remove the Ajax because you do not needed and make a regular full post back when the user submit their data.
Then when you make back with the browser, browser load the previous state and most of the browsers remember what and all the input of the user. Also on that back the viewstate is the same as previous because did not have change from the Ajax.

How to use a form with GET to utilize querystring, but not have VIEWSTATE in querystring?

I'm trying to create a C# webpage that uses a GET method so I can bookmark form data, email it to other people, etc., but changing the form method to GET results in the querystring containing the VIEWSTATE. I can take out the runat=server tags (as mentioned here) but then I don't know how to set the values of my form fields. I don't mind manually persisting them, but I can't figure out how.
So, how do I either utilize the viewstate but keep it out of my querystring, or access the form controls without runat=server?
If you are using, for example, a search/filter form on your webpage that you want via GET, here's a pattern I've used multiple times in my own code. When the user submits a button to process what they've entered in the form, I let it hit my code-behind as a POST as normal. Then I manually construct a GET request and redirect to it:
protected void BtnSubmit_Click(object sender, EventArgs e)
{
var query =
"?filter1=" + TxtFilter1.Text +
"&filter2=" + TxtFilter2.Text +
"&filter3=" + TxtFilter3.Text; // etc.
Response.Redirect(query);
}
Then on load of the page, I process the entries in the query string to pre-populate the relevant form controls on the page:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TxtFilter1.Text = Request.QueryString["filter1"] ?? "";
TxtFilter2.Text = Request.QueryString["filter2"] ?? "";
TxtFilter3.Text = Request.QueryString["filter3"] ?? "";
// etc.
}
}
This allows me to have control over what actually goes into the QueryString without messing with the built-in form POST managed by ASP.Net (including View State). Also, when a user has filled out the form and pressed the button, they have a linkable url, and even though it was a POST, if they refresh the page they don't get that annoying message about re-sending data to the server.

Categories