How to delete a button click event? - javascript

In my project, there is a asp button with a C# button_Onclick handler. The problem is when you click the button on html, the event will be kept by browser. For example, the event will be sent if you refresh the browser..
I have tried add a return; to the end of the button_Onclick handler and a JavaScript for thebutton_Onclick handler to call, but all fail.
asp:
<asp:Button ID="btnSubmit" runat="server" Text="Save" />
C#:
protected void btnSubmit_Click(object sender, EventArgs e)
{
.......
return;
}

Assuming your code makes a POST request when clicking the button, this is how browsers behave and should behave on refresh. They must send the submitted data again to the server. If you want to avoid this, then in your submit handler method you should do a redirect to another URL after doing whatever your handler does.
For example if form.asp displays your form, then in your handler you can redirect to form.asp?message=thankyou (notice the different URL), then in case of refresh, your form will not be sent again by the browser to the server.
Also, best would be to use a 303 redirect.

You should redirect to another page to avoid this.But In case if you want to stay on the workaround is as follows.
In your pageload_Event capture the dateTime.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["update"]=Server.UrlEncode(System.DateTime.Now.ToString());
}
}
In the Page_PreRender Event Copy the sessionVariable to ViewState Variable.You can refer following to get a clear understanding on Page Life cycle. "http://www.codeproject.com/Articles/667308/ASP-NET-Page-Life-Cycle-Events"
public void Page_PreRender(object obj, EventArgs e)
{
ViewState["update"] = Session["update"];
}
Now in your button on click event compare the ViewState ans session variable.Allow into the block if both the values are equal.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Session["update"].ToString() == ViewState["update"].ToString())
{
try
{
-----------Your Logic
}
finally
{
Session["update"]=Server.UrlEncode(System.DateTime.Now.ToString());
}
}
}

Related

Trying to access server side variable from javascript

i have a page where in the form load i initialize a server side variable with value and i want to render that value in js section. i am working with asp.net webform apps.
my server side page load code
string errblankEmail ="";
protected void Page_Load(object sender, EventArgs e)
{
errblankEmail ="Hello World";
}
if (str == '') {
alert('<% =errblankEmail %>');
}
when i run the page then i am getting error message like
CS0103: The name 'errblankEmail' does not exist in the current context
and i also saw that my page_load is not getting called because i set break point there.
so guide me how to fix this problem. thanks
You have to make the variable public in order to access it.
public string errblankEmail ="";

ASP.NET - Call javascript validation function before submitting form

I need to implement some 3rd-party field validation in our site's forms. Currently, the validation of our form fields is done by using ASP.NET validators (required, regex) and I'd like to continue use of these on the fields where we won't be using the new validation. The company providing us with the new validation services gave us all of the code to integrate into our site to get the new validation functioning, and the basic implementation just requires us to call a javascript method that reads the values of specified fields and validates them via a few service calls. Also, the implementation requires that the form initially has the onsubmit="return false;" attribute set.
The issue that I'm running into is when the validation script is attempting to submit the form, (after a post-validation function removes the form's onsubmit attribute) since event validation is turned on (not an option to turn off), the page throws the exception "Invalid postback or callback argument". Perhaps I've provided an excess of details to give context, but maybe the question boils down to: Can you submit an ASP.NET form using javascript if event validation is enabled without causing this error? And if so, how?
You can invoke a post back in your JavaScript function, like this:
<script type="text/javascript">
function DoValidation(parameter)
{
// Do calls to validation services here
// If all validation passes, then call this
if(valid) {
__doPostBack('btnSave', parameter)
}
}
</script>
<asp:Button id="btnSave" runat="server" OnClientClick="DoValidation()"
Text="Save" />
Note: btnSave is a made up name, but it should represent the server-side control that would normally be doing the post back.
Now in your page's Page_Load event, you can determine who initiated the post back and any data sent with it, like this:
protected void Page_Load(object sender, EventArgs e)
{
// Get the control that caused the post back (btnSave)
Request["__EVENTTARGET"];
// Get the parameter value (parameter)
string parameter = Request["__EVENTARGUMENT"];
}
Yes, you can. Something like this, and please bear with me, this is merely pseudo code.
<header>
<script type="text/javascript">
function JavaScriptSave()
{
// Validations here
if(passed)
{
__doPostBack('<%=MyButton.ClientID %>','OkToSave');
}
}
</script>
</header>
<asp:button id="MyButton" runat="server" Text="Submit Button" OnClientClick="JavaScriptSave()" />
Then on the back side:
protected void Page_Load(object sender, EventArgs e)
{
string passedInValue = Request["__EVENTARGUMENT"];
if(passedInValue = "OkToSave")
{
// perform save function here
}
...
if(IsPostBack)
return;
}

ASP.NET- Prompt confirmation only if needed

I have a button. And I have a Session["actionMode"]. Here what I do in my buttonClick event:
protected void Button1_Click(object sender, EventArgs e)
{
if ((int)Session["actionMode"]==1)
{
//Do something
}
else if ((int)Session["actionMode"]==3)
{
//After confirmation delete a record
}
}
As you can see if value of Session["actionMode"] equals 3 a record is deleted. But before deletion I want to prompt the user to confirm the action. So if value of Session["actionMode"] does not equal 3 I don't need any confirmation because it does not do anything that can't be undone. Is there a way I can achieve this? Javascript maybe?
This code block...
{
//After confirmation delete a record
}
You are executing server side code, and in need for user interaction.
Whatever you do (client or server) you have to split this. A server side alternative.
{
// Display a confirmation including server side controls.
}
protected void YesDeleteTheDamnRecord_Click(object sender, EventArgs e)
{
// Delete it now.
}
And here is one solution with client side interaction.
Check the value of "actionMode" way before displaying Button1.
If it's equal to "3" attach a client side event handler to Button1.OnClientClick.
Display a confirmation (window.confirm maybe)
If user clicks "Yes" execute server side code and delete the record.
I would suggest you to use following approach for deletion.....
protected void Button1_Click(object sender, EventArgs e)
{
if ((int)Session["actionMode"]==1)
{
//Do something
}
else if ((int)Session["actionMode"]==3)
{
//Call Javascript Function which will call Ajax
}
}
Javascript:
function callAjax()
{
if(confirm(do you want to delete data?))
{
call Ajax Page
}
else
{
return;
}
}
Ajax Page:
PageLoad
{
Get Session["actionMode"] Value
Do your Delete here...
}

how to access javascript querystring in codebehind?

im sending a value from one page in aspx to another page as shown below.
window.location="test1.aspx?id=1"
how to access this value in codebehind or global.asax?
You could retrieve the id parameter from the Request object in your code behind:
protected void Page_Load(object sender, EventArgs e)
{
string id = Request["id"];
// do something with the id
}
Also you will have to fix your javascript because the url you are assigning is invalid. You have an extra + character that should be removed:
window.location.href = 'test1.aspx?id=1';
Leave the + sign out and use the Request.QueryString object.
window.location="test1.aspx?id=1"
string v = Request.QueryString["id"];

Call client script from button with submit behaviour false?

How do I call a client script function from a server side button click(with submit behaviour set to false) .
protected void Button4_Click(object sender, EventArgs e)
{
//System.Threading.Thread.Sleep(2000);
lbDateTime.Text=System.DateTime.Now.ToString();
ClientScript.RegisterClientScriptBlock(this.GetType(),"success","saveSuccess()");
}
You should set the OnClientClick attribute of the Button like
OnClientClick="saveSuccess(); return false;"
this way you keep the sumbit behaviour to false, and you also call the client script function.
Also, if you want to do this via server side code you can add this to your Page_Load
Button4.Attributes["OnClientClick"] = "saveSuccess(); return false;";
However, if you want to call the script after the "save" has completed, and you are using asynchronous jobs, and an UpdatePanel, then you should call
ScriptManager.RegisterClientScriptBlock(typeof(Page), "savescript", "saveSuccess();", true);
after the asynch job has finished, and the data have been saved.
ClientScript.RegisterStartupScript(this.GetType(), "success", "saveSuccess()", true);

Categories