GridView_RowCommand event fired again on page refresh - asp.net

I have implement GridView Row Editing feature in my .net application using <asp:CommandField.
I clicked on Update button to save the record after editing the row.Now if i refresh the page or press F5 GridView_RowCommand fired again.
How can we avoid this.Is there any mechanism to identify when user press F5 OR refresh the page.Is there any method in client side or in server side.

Not exactly the best "technical" solution to your problem but you could always just do a Response.Redirect(Request.RawUrl) once you have finished doing anything you need to do in your RowCommand
Like I said, it's not the best "technical" solution but it is a solution
Dave

One method of capturing this is to maintain a session variable that is related to the page in question. In the session variable you would keep some kind of state enumeration, key or string that would determine the last action taken. You could even use a simple incremented counter, and if you ever received a postedback counter that was equal to the session variable it would indicate a page refresh rather than a new action.

Session["LastInsertedItem"] = null;
MyCustomObjType myCustomObject;
protected void Page_Load(object sender, EventArgs e)
{
myCustomObject = Session["LastInsertedItem"] as MyCustomObjType;
}
void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
If(myCustomObject == null || //!(compare your value with myCustomObject.field) )
{
// do your operations and save the values to myCustomObject and save that object back to Session.
}
else
{
// It is refreshed or same data is being insterted - don't know if second option is possible in your case.
}
}

Related

ASP.NET Session and Page Life Cycle

Let's say that in an ASP.NET .aspx page I have the Page Load method and another method for a button click event.
In the Page Load method I'm checking if the user is logged in by checking the Session. Whether he is or not, I'm storing the result in a Global Variable.
Boolean isGuest = false;
protected void Page_Load(object sender, EventArgs e) {
if(Session["id"]==null)
isGuest = true;
else
isGuest = false;
}
Let's say 20 minutes have passed, and I don't know if the Session has terminated or not, and then I click a Button, the event goes like this:
protected void Button_Click(object sender, EventArgs e) {
if(isGuest==false)
//do something
else
// do another thing
}
My Question is : When I'm clicking the button, does ASP.NET go through the Page_Load method again (check isGuest again) or it simply executes what's inside the Button_Click method, means, it uses a Boolean isGuest that could be false, but in reality the session is terminated, means it should be true.
Page_Load is triggered always before the control events.
Have a look: ASP.NET Page Life Cycle Overview
Side-note: If you want to do things only on the first load and not on every postback you have to check the IsPostBack property.
You can:
Define your own class with the UserID, and other profile properties;
Add that class to session in the global.asax session started event Session["NameReferingToYourClass"] = new YourClass();
Set a member variable to your session object early in the page life cycle mYourClass = Session["NameReferingToYourClass"] casted if you need to;
Then you can make any changes to your class anywhere in the code your member variable is available;
Save back your class with all the changes into session on the Page.Unload(..){ Session["NameReferingToYourClass"] = mYourClass.
This way you are using your class properties in your code, including UserId, pretty much like a windows application, there will be no mentioning of session anywhere else in your code.

Linq data not updating form after postback

In my application, I have a form that users fill out, then gets approved by a manager. I have various types of forms that all use the same process, so the approval buttons are all done via a user control (which includes the functionality to update the data in the database and call the postback).
However, once I click on the "Approve" button (which is in the user control), the form information doesn't update (it still says "unapproved"). A postback is definitely happening, but not sure why the page isn't updating properly.
I can confirm that the change are being made - when I manually reload the page, it gets updated - but not on the post back.
What am I missing here?
My page:
protected void Page_Load(object sender, EventArgs e)
{
int ID;
// ensure that there's an ID set in the query string
if (Int32.TryParse(Request.QueryString["ID"], out ID))
PopulatePage(ID);
else
Response.Redirect("~/Default.aspx");
}
}
protected void PopulatePage(int ID)
{
using (WOLinqClassesDataContext db = new WOLinqClassesDataContext())
{
lblStatus.Text = wo.Workorder.status;
....
}
}
I think that the Page_Load happens before the code in the submit button. To check this just use a couple of breakpoints. So the page loads the old data since the new data are not saved yet.
You should call a method to load the data inside the OnClick method of the Approve button.
After you've submitted the changes to the database, try running db.Refresh(RefreshMode.OverwriteCurrentValues) to force the changes to be reloaded into the data context.

hook POST parameters in asp.net

I'm recently mining a website to build some database. I already built a python script parsing retrieved information but the problem is that it requrires a query word to retrieve web pages which contain information I want to see. And this page is in POST method so I cannot see how this page retrieves a page list.
To describe an outline for your clear understanding:
1. on inputKeyword.aspx : This contains a form to input a query(let's say ID)
When I input an ID and press search, it retrievs a
relevant list
2. Press Search
3. on inputKeyword.aspx : A relevant list is showed on the same aspx page
(which means POST method), so I cannot see how this query
works on inputKeyword.aspx page.
It would be so much easier if this webpage is in GET method, since I can simply hook a url with queries, but it's not possible in POST method.
Is there any way that I can open step #3 skipping step #1 and #2?
The webpage is built in asp.net but there's no restriction on languages as long as there's way to do this.
If I understand correctly you want to be able to accept a an ID as part of your query string. eg
http://your.domain.com/inputKeyword.aspx?ID=555
So in the pages load event you can check the request object for query params, ie Request.QueryString[param] as the following example shows
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["ID"];
if (!string.IsEmptyOrNull(id))
{
//do something with the requested identifier
}
}
Note: you can use Page.IsPostBack() to determine if the page is being hit for the first time or is posting back as a result of a button click.
To get your Search button to behave correctly you have a couple of options. For example; you can use javascript to capture the buttons onclick event and redirect the page to itself with the url amended to include the identifier from the id textbox.
But perhaps the following is the easiest, keeping the code all server-side:
private _identifer string;
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["ID"];
if (!string.IsEmptyOrNull(id))
{
_identifer = id;
}
}
protected void SearchButton_Click(object sender, EventArgs e)
{
_identifer = IdentiferTextbox.Text;
}
protected void Page_PreRender(object sender, EventArgs e)
{
if (!string.IsEmptyOrNull(_identifer))
{
PopulateListForidentifer(_identifer);
}
}
Basically the example shows that you can cope with scenarios. ASP.Net's page life cycle means that events are processed in the following order Page_Load -> Control Events (eg button click) -> Page PreRender.
If the page is hit for the first time without an identifier in the url, PopulateListForidentifer method isn't called since _identifer is never set.
But if the url contains an identifier then _identifer is set in the page load event, when the page pre-render is called PopulateListForidentifer will be called.
Finally if the page is posting back to itself because the search button has been hit then the click handler is called and _identifer is set to the content of the IdentiferTextbox; the pages prerender is called and also PopulateListForidentifer. Note this would override the point about ie when the identifer was passing as part of the url.
From what I understand, it seems you want to simulate the HTTP Post operation in your Search form, where by without entering the ID and clicking search, you directely want to have access to the search results.
Here is a Blog Post by Scott Hanselman, where he discusses a similar topic using WebClient.
You may also want to check this thread

Best way to "save" a value in a textbox (ASP.NET)?

I have a textbox where the user enters some data and saves this value to the database. Next time the user comes to the same aspx page in the same session, the value should be restored in the textbox. Whats the best way to do this? Using the session maybe?
Thanks :-)
The session is a good way to save the data. You also should have a way to load the data from the database if the session is not available. (ie, they come to the same page the next day)
something like this:
public string MyVariable
{
get
{
if (Session["MyVariable"] == null)
{
Session["MyVariable"] = LoadFromDatabase();
}
return Session["MyVariable"];
}
}
protected void Page_Load(object sender, EventArgs e)
{
MyTextBox.Text = MyVariable;
}
Using the session, you will be able to do it only within a session unless you maintain a session in state server or in database.
For the first time, store the user entered text into the session and also update it in the Database. Later, whenever you need to show this value to the user, check whether the textbox value exits in the session. If not, then read it from the database, update the session with the value and show it to the user.

need suggestion on C# coding (efficiency)

In my code I have a dropdown selection and upon selection from dropdown the code performs further processing and generates report/data.
Further, the entire program depends on data which is gathered from 3 different operation
Operation1: processing a text files of size of size > 6MB
Operation2: SQL Query to a DB (Query takes around 1 minute)
Operation 3: HTTP POST request to server (The main costliest part of the programe)
So, to make it efficient I am thinking to perform this operation only once and use the data for all the different selection from dropdown.
Question is how can I do so as below:
I can't put it in "page_load" event because every time page loads the operations will carry out
I can't put it inside "dropdownlist_selectedindexchanged" event because then it will be same as #1.
I thought of doing it in "page_load" as below
void Page_Load(object sender, EventArgs e)
{
if(!ispostback)
{
Operation1();
Operation2();
Operation3();
}
}
This is fine; the operations gets performed only once and I can use the data throughout, but then my page will take time to load as the operations takes time.
Is there any other way I can achieve what I want? Please let me know.
Thanks,
Rahul
If the data set will not change, you probably could manage to do it once at Application_Start().
Edit - something like this (typing from memory and away from VS, i do VB):
Protected void page_load(object sender, eventargs e)
{
// the name can be anything
if (!System.Web.HttpContext.Current.Session["data_cache_filled"])
{
// code to fill the cache.
// ...
//mark it as filled
System.Web.HttpContext.Current.Session["data_cache_filled"] = "yes";
}
}
Cache it. Using the CacheHelper class from here, you could do:
internal List<Employee> Operation1()
{
List<Employee> employeeData;
if (!CacheHelper.Get("employeeData", out employeeData))
{
employeeData = (from x in db.Employees select x).ToList(); // or whatever
CacheHelper.Add(employeeData, "employeeData");
}
return employeeData;
}

Resources