I have a button on an ASP.Net page that will call Response.Redirect back to the same page after performing some processing in order to re-display the results of a query. However, for some reason, the page comes up blank. It seems that IsPostBack is returning true after the redirect. Anybody know why this would happen?
The page is a custom page in Community Server. Here is the basic code:
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ge_vw_NonResidents", connStr);
DataTable tbl = new DataTable();
da.Fill(tbl);
da.Dispose();
rptNonResidents.DataSource = tbl;
rptNonResidents.DataBind();
}
}
void btnApprove_Command(object sender, CommandEventArgs e)
{
// Code removed for testing.
Response.Clear();
Response.Redirect("ApproveResidents.aspx", true);
Response.End();
}
A Response.Redirect will trigger an HTTP GET from the browser. As no data is posted, IsPostBack is false. You have something else going on.
I'd suggest firing up Fiddler and looking at the sequence of requests. It should look something like:
Client: HTTP POST (button click)
Server: HTTP 302 (Redirect)
Client: HTTP GET
Server: HTTP 200 (Writes page)
I suggest this as a better solution to your problem than attempting to redirect from the browser.
protected void Page_Load( object sender, EventArgs e )
{
if (!IsPosBack) {
BuildData();
}
}
void btnApprove_Command(object sender, CommandEventArgs e)
{
// do your stuff and clear any some controls, maybe
BuildData();
}
private void BuildData()
{
string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ge_vw_NonResidents", connStr);
DataTable tbl = new DataTable();
da.Fill(tbl);
da.Dispose();
rptNonResidents.DataSource = tbl;
rptNonResidents.DataBind();
}
Sorry, it was an id-10-t error. My event handler wasn't getting called at all. The page had EnableViewState="false". Once I changed that to true it worked.
I also took tvanfosson suggestion. This allows me to display a confirmation message. I can easily check to see if the action has already been taken and safely ignore it. Since I'm likely the only one to ever see this screen, I'm not too concerned with usability.
Response.Redirect(url,true);
this worked for me.
The page is posted back , that is why you're getting it as true. make sure it is false.
Related
Consider this code
DataTable dt = new DataTable() ;
protected void Page_Load(object sender, EventArgs e)
{
dt.Columns.Add("RowIndex");
dt.Columns.Add("FilterText");
}
I will Fill this data table by some data during executing program. but when i click a button , the page will reload the codes and my data will be lost.
how can i prevent the web form from creating new data table and save my data?
my controls are inside an update panel.
A new instance of the class is created for each request. If you want to save things from one request to another you need to use a different mechanism.
For example a global. But on top of a globals usual problems you need to handle multiple concurrent requests and thus multi-threading and locking.
The usual approach is to store persistent state in a database, loading the information for each request at the start of processing that request.
You can use View State to solve problem..
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dt = new DataTable();
dt.Columns.Add("RowIndex");
dt.Columns.Add("FilterText");
}
else
{
if (ViewState["vsDT"] != null)
dt= ViewState["vsDT"] as DataTable;
}
}
Hi i wanted to know if there is any way that i can reset my form after the data has been added successfully into the database? Like after showing some message to the client the textbox should automatically clear out.
What should I write in this block:
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Label2.ForeColor = System.Drawing.Color.DeepSkyBlue;
Label2.Text = "Master added successfully";
}
else
{
Label2.Text = "Master not added";
}
2 ways :
You can do it in server side :
TextBox.Text=string.Empty; (at PageLoad or PreRender). ( I'd choose Prerender cuz your form might use the old value...)
You can do it using javascript/jQuery :
$(function (){$("form")[0].reset()});
or this.form.reset()
I have a GridView and on its SelectedIndexChanged the code is fired:
protected void grdEntry_SelectedIndexChanged(object sender, EventArgs e)
{
lblAssignId.Text = grdEntry.SelectedRow.Cells[1].Text == " "
? ""
: grdEntry.SelectedRow.Cells[1].Text;
Ob.BranchId = Globals.BranchID;
Ob.AssignId = lblAssignId.Text;
DataSet dsMain = GetAssignDetails(Ob);
if (dsMain.Tables[0].Rows.Count != 0)
{
// some other code
Task.Factory.StartNew(() => FillMemberShipAndBarCode(dsMain.Tables[0].Rows[0]["CustomerCode"].ToString(), Ob.BranchId));
}
}
and the code for filling membership id is
private void FillMemberShipAndBarCode(string customerCode, string branchId)
{
var sqlCommand = new SqlCommand
{
CommandText = "sp_customermaster",
CommandType = CommandType.StoredProcedure
};
sqlCommand.Parameters.AddWithValue("#CustomerCode", customerCode);
sqlCommand.Parameters.AddWithValue("#BranchId", branchId);
sqlCommand.Parameters.AddWithValue("#Flag", 18);
var data = PrjClass.GetData(sqlCommand);
txtMemberShip.Text = data.Tables[0].Rows[0]["MembershipId"].ToString();
txtBarCode.Text = data.Tables[0].Rows[0]["Barcode"].ToString();
}
It's working fine, but is is not updating any of the textboxes. Also, I checked in watch window, the values are returned as expected (M-1213 and 634-98-4 ) and the code does reaches the point txtMemberShip.Text = data.Tables[0].Rows[0]["MembershipId"].ToString();
but the txtMemberShip just remains empty??? Can anyone tell me why is not updating the textboxes?
UPDATE
As per comments, here is the page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDown();
BindGrid();
SetDefaultsInTextBoxes();
}
}
And I don't have any code that waits on this task.
Don't do this:
Task.Factory.StartNew(() => FillMemberShipAndBarCode(dsMain.Tables[0].Rows[0]["CustomerCode"].ToString(), Ob.BranchId));
What are you trying to achieve by doing so?
What is probably happening is your method FillMemberShipAndBarCode is probably running after ASP.NET has already sent the page back to the browser. Thus, essentially, no visible effect on the rendered HTML.
ASP.NET isn't a good place to do multi-threaded stuff.
Try just replacing the above with this:
FillMemberShipAndBarCode(dsMain.Tables[0].Rows[0]["CustomerCode"].ToString(), Ob.BranchId);
I am trying to submit filledin information in the form to the database. I have done the below mentioned coding for the save button. When I click on the save button to save the information, I am getting an error. I need it to be done and for the same need help from the geeks around here.
COde for SAVE button data from database
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string conn = ConfigurationManager
.ConnectionString("welcome").ConnectionString;
SqlConnection con=new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("Insert into abhishek(pr_name,Add,add2) values(#ah,#Ap,#qe)",con);
cmd.CommandType = CommandType.Text;
cmd.Parameter.Addwithvalue("#ah", TextBox1.Text.Trim());
cmd.Parameter.Addwithvalue("#ap", TextBox2.Text.Trim());
cmd.Parameter.Addwithvalue("#qe", TextBox3.Text.Trim());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Check the error in the image below:
You are missing an 's' from the ConnectionStrings indexed property. Once you fix that error, however, you will also find you are missing more 's' from the SqlCommand.Parameters property.
To reveal these issues, open Properties of your code-behind file, and choose Build Action of Compile. (Also, I can see from your image that it looks like your project is setup as a Web Site rather than a Web Application; if possible, look into converting this over to a Web Application, as it offers a number of benefits.)
Once you get your syntax corrected, then you should change your code so that the update is invoked through the button click handler, rather than on page load.
In your markup code in the aspx:
<asp:Button runat="server" ID="btnSave" Text="Save" OnClick="btnSave_Click" />
In your code-behind:
protected void btnSave_Click(object sender, EventArgs e)
{
string conn = ConfigurationManager.ConnectionStrings["welcome"].ConnectionString;
using (SqlConnection con = new SqlConnection(conn))
{
SqlCommand cmd = new SqlCommand("Insert into abhishek(pr_name,Add,add2) values(#ah,#Ap,#qe)", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ah", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("#ap", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("#qe", TextBox3.Text.Trim());
con.Open();
cmd.ExecuteNonQuery();
}
}
Note that I have moved the code into the button click event handler, and out of the Page_Load. The Load event handler should only be used for initialization items needed unconditionally on the execution path of the page (i.e., regardless of whatever button was clicked on the page), and should look something like the following:
protected void Page_Load(object sender, EventArgs e)
{
// Code to run every time the page is created, both initially and on postback
if (IsPostBack)
{
// Code to run every time the page is posted back (any submit event)
}
else
{
// Code to run on the initial creation of the page
}
}
Duplicate of Asp.Net Button Event on refresh fires again??? GUID?
hello, ive a website and when a user click a button and the page postback, if the user refresh the Page or hit F5 the button method is called again.
any one know some method to prevent page refresh with out redirect the page to the same page again ?
something like if (page.isRefresh) or something... or if exist any javascript solution is better.
this seen to works.... but when i refresh it does not postback but show the before value in the textbox
http://www.dotnetspider.com/resources/4040-IsPageRefresh-ASP-NET.aspx
private Boolean IsPageRefresh = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["postids"] = System.Guid.NewGuid().ToString();
Session["postid"] = ViewState["postids"].ToString();
TextBox1.Text = "Hi";
}
else
{
if (ViewState["postids"].ToString() != Session["postid"].ToString())
{
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Session["postid"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (!IsPageRefresh) // check that page is not refreshed by browser.
{
TextBox2.Text = TextBox1.Text + "#";
}
}
Thanks for comments and sorry for my mistake,
I found this code in:
http://www.codeproject.com/KB/aspnet/Detecting_Refresh.aspx
And this time tested ;)
private bool _refreshState;
private bool _isRefresh;
protected override void LoadViewState(object savedState)
{
object[] AllStates = (object[])savedState;
base.LoadViewState(AllStates[0]);
_refreshState = bool.Parse(AllStates[1].ToString());
_isRefresh = _refreshState == bool.Parse(Session["__ISREFRESH"].ToString());
}
protected override object SaveViewState()
{
Session["__ISREFRESH"] = _refreshState;
object[] AllStates = new object[2];
AllStates[0] = base.SaveViewState();
AllStates[1] = !(_refreshState);
return AllStates;
}
protected void btn_Click(object sender, EventArgs e)
{
if (!_isRefresh)
Response.Write(DateTime.Now.Millisecond.ToString());
}
You can test for the Page.IsPostBack property to see if the page is responding to an initial request or if it's handling a PostBack such as your button click event. Here's a bit more information: w3schools on IsPostBack
Unfortunately that's not going to solve your problem since IsPostBack will be true when the user clicks the button as well as when they refresh the page after the button action has taken place.
If you're doing a task like performing CRUD on some data, you can Response.Redirect the user back to the same page when you're done processing and get around this problem. It has the side benefit of reloading your content (assuming you added a record to the DB it would now show in the page...) and prevents the refresh problem behavior. The only caveat is they still resubmit the form by going back in their history.
Postbacks were a bad implementation choice for the Asp.net and generally are what ruin the Webforms platform for me.
This doesn't solve the problem.
First of all, storing a token in the view state is not a good idea, since it can be disabled. Use control state instead. Although, a HttpModule is a better solution.
All in all, this will not work anyway. If you open another tab/window the session will be invalid for the previous tab/window. Therefore braking it. You must somehow store a unique value each time a page is first loaded. Use that to determine where the request came from and then check the "refresh ticket". As you may see, the object for one user might get pretty big depending on the amount of requests made, where and how long you store this information.
I haven't seen any solution to this I'm afraid, as it is pretty complex.
bool IsPageRefresh ;
if (Page.IsPostBack)
{
if (ViewState["postid"].ToString() != Session["postid"].ToString())
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postid"] = Session["postid"];
I tried many ways and I ended up looking for the form data sent when the postback / refresh is triggered... I found that there is a Key for any VIEWSTATE created and you can just compare those Keys like...
I put that on my custom basepage to reuse it like an Property
public bool IsPageRefresh = false;
protected void Page_Init(object sender, EventArgs e)
{
if (IsPostBack)
{
var rForm = Request.Form;
var vw = rForm["__EVENTVALIDATION"].ToString();
var svw = Session["__EVENTVALIDATION"] ?? "";
if (vw.Equals(svw)) IsPageRefresh = true;
Session["__EVENTVALIDATION"] = vw;
}
}