My C# code does not run until I click again - javascript

im calling a JS function inside a c# method in ASP, this is my html:
<asp:Button runat="server" id="Button1" CssClass="btns" Text="test confirm delete" OnClick="testDelete"/>
and this is the testDelete method:
protected void testDelete(object sender, EventArgs e) {
int x = 0;
int y = 2;
int res = x + y;
if (res > 1) {
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "testDel()",true);
if (hc2.Value == "true") {
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Ok');", true);
//Here im gonna do a SQL Delete Query
}
}
}
and this is the JS function
function testDel() {
document.getElementById("hc2").value = confirm("you want to delete?").toString();
console.log(document.getElementById("hc2").value);
}
As you can see in the JS function i am assigning the confirm value to my "hc2" element of the html, and I use that same element in my C# code to check if the user clicked YES or CANCEL, and if the user clicked OK the Alert and the SQL query runs.
the assignment of the confirm value to "hc2" element works, but the alert does not work until I click the button again.

here's a bit of JavaScript you can use that replaces the code behind logic. Once you get a confirmation, call the codebehind function via JavaScript.
html:
<asp:button id="BtnConfirm" Runat="Server" OnClientClick="testDelete()" /> <br>
<asp:button id="BtnYes" Runat="Server" OnClick="ASPFunction" visible="false" />
JavaScript:
function testDelete() {
var x = 0;
var y = 2;
var res = x + y;
if (res > 1) {
var rslt = confirm("Do you want to delete?");
}
if (rslt == true) {
document.getElementById("BtnYes").click();
} else {
// block of code to be executed if the condition is false
}
}
and CodeBehind:
protected void BtnYes(object sender, EventArgs e) {
//sql stuff goes here
}

Related

Confirm messagebox not working correctly

The below code runs a confirm messagebox with yes no on Asp.Net.
I need to detect the value if its confirmed or not.
How can I do this ?
Aspx :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to save data?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="btnConfirm" runat="server" OnClick = "OnConfirm" Text = "Raise Confirm" OnClientClick = "Confirm()"/>
</form>
</body>
</html>
Code behind :
protected void OnConfirm(object sender, EventArgs e)
{
// This method runs even though the user clicks no.
}
Update :
With this code, both yes or no selections runs the same method named OnConfirm.
So I try to run the OnConfirm method only if the user clicks yes.
Update:
you can use a hidden field with runat=server and save yes/no. then send it to server.
<input type="hidden" runat="server" value="" id="hidden1" />
function Confirm() {
if (confirm("Do you want to save data?")) {
confirm_value.value = "Yes";
document.getElementById("hidden1").value = "yes";
} else {
confirm_value.value = "No";
document.getElementById("hidden1").value = "no";
}
document.forms[0].appendChild(confirm_value);
}
If you use a master page, remember that client id of hidden is different with its server id.
protected void OnConfirm(object sender, EventArgs e)
{
string confirmValue = hidden1.Value;
}
i think what you want to do is only execute the server side button when the user confirms OK right? if yes, then just do this, basically when the javascript function returns false, the server side button will not fire ie: (OnClientClick = "return Confirm()")
<script type = "text/javascript">
function Confirm() {
return confirm("Do you want to save data?");
}
</script>
<asp:Button ID="btnConfirm" runat="server" OnClick = "OnConfirm" Text = "Raise Confirm" OnClientClick = "return Confirm()"/>

ASP Web Forms fire code behind event on condition

I have ASP.NET WEB FORMS apps
<asp:Button ID="DeleteDealsButton" runat="server" Text="Delete" />
function btnDeleteClick() {
var result = confirm("Want to delete all Deals?");
if (result) {
return true;
} else {
return false;
}
}
$("#MainContent_DeleteDealsButton").on("click", function() {
if (btnDeleteClick()) {})
On this button I have sample javascript alert to ask OK or Cancel.I want if choise OK to fire CODE BEHIND method call DeleteDealsButton_Click, if it Cancel to do nothing.
Just change button defination to,
<asp:Button ID="DeleteDealsButton" runat="server" Text="Delete" OnClientClick="return confirm('Want to delete all Deals?')" />
No need for any javascript function.
try like this:
function btnDeleteClick() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
confirm_value.value = "No";
var result = confirm("Want to delete all Deals?");
if (result) {
confirm_value.value = "Yes";
__doPostBack('DeleteDealsButton', '')
return true;
} else {
confirm_value.value = "No";
return false;
}
}
In your .Aspx file Change your button code to like this:
<asp:Button ID="DeleteDealsButton" OnClientClick=" return btnDeleteClick()" runat="server" Text="Delete" OnClick="DeleteDealsButton_Click" />
In your .Aspx.cs file
protected void DeleteDealsButton_Click(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (!String.IsNullOrWhiteSpace(confirmValue) && confirmValue.Equals("Yes"))
{
}
}

Validation not working when adding query string

My validations are not working when redirecting from one page to another on passing query string as a parameter with response.redirect or with windows.location.href.
When I am redirecting from one page to another page with this:
<asp:Button ID="New" runat="server" Text="New" OnClientClick="Transfer()" />
function Transfer() {
window.location.href = "Abc.aspx?flag=yes"; //when adding query string my validation doesnt work
//window.location.href = "Abc.aspx";// When removing query string my validation successfully works
}
Then I have tried from server side like this:
<asp:Button ID="New" runat="server" Text="New" OnClick="New_Click" />
protected void btnNewApplicant_Click(object sender, EventArgs e)
{
Response.Redirect("Abc.aspx?flag=yes", false); //again not working with this.
}
When I click on this New button i am getting error in console:
Is this error has to do anything with this option: EnableEventValidation="false" as you can see in my code?
Note: I need to pass parameter as query string for some reason.
Abc.aspx:
<%# Page Title="" Theme="---" Language="C#" MasterPageFile="---" AutoEventWireup="true" CodeBehind="---" EnableEventValidation="false" Inherits="---" %>
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rf1" runat="server" ErrorMessage="require" ForeColor="Red" ControlToValidate="txt1" Display="None" ValidationGroup="validate"></asp:RequiredFieldValidator>
<asp:TextBox ID="txt2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rf2" runat="server" ErrorMessage="require" ForeColor="Red" ControlToValidate="txt2" Display="None" ValidationGroup="validate"></asp:RequiredFieldValidator>
<asp:Button ID="btnSubmit" runat="server" Text="Save" ValidationGroup="validate" OnClick="btnSubmit_Click" UseSubmitBehavior="true" OnClientClick="checkvalidation()"/> //on click of this i want to perform validation but it is not working.
<telerik:RadCodeBlock ID="radcodeblock1" runat="server" EnableViewState="true">
<script type="text/javascript">
function checkvalidation() {
window.Page_ClientValidate('validate');
var counter= 0;
var val= '';
for (var i = 0; i < window.Page_Validators.length; i++) {
if (!window.Page_Validators[i].isvalid && typeof (window.Page_Validators[i].errormessage) == "string") {
counter= 1;
val+= '- ' + window.Page_Validators[i].errormessage + '<br>';
}
}
if (counter== 1) {
//My validation pop up to display validations alert because this counter value remains 0 so this part is not executed.
}
}
</script>
</telerik:RadCodeBlock>
Now when I click on submit button then my server side code event is fired but my validation pop up doesn't appear.
I have even put this line in web.config:
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None"></add>
But this is still not working as removing query string from response.redirect or from windows.location.href then my validation pop up successfully appears and it is working fine.
If, as you say, window.Page_Validators[i].isvalid is false and typeof (window.Page_Validators[i].errormessage) is true, then we must go into the 'if' condition. The counter must be set to 1, and then must go into the 'if' later on.
I've changed the checks a little bit and have added the console logging to help you. In case anyone doesn't know, you can view these messages by hitting F12 in the browser and clicking "Console".
function checkvalidation() {
window.Page_ClientValidate('validate');
var counter= 0;
var val= '';
for (var i = 0; i < window.Page_Validators.length; i++) {
if ( (window.Page_Validators[i].isvalid === false) && typeof (window.Page_Validators[i].errormessage) == "string") {
console.log("Inside the if condition");
console.log(window.Page_Validators[i]);
counter = 1;
val+= '- ' + window.Page_Validators[i].errormessage + '<br>';
}
}
if (counter === 1) {
//My validation pop up to display validations alert because this counter value remains 0 so this part is not executed.
}
}

RegisterStartupScript shows message after function ends

i want to show a javascript confirm box on the client side under OnChange event "chkIsActive_CheckedChanged". i am using registerStartupscript int the code behind for this purpose. this confirm message is displaying fine but it is displaying after end of the event "chkIsActive_CheckedChanged". i want to display the confirm message while executing in the function. Please help me out.
My HTML
<asp:CheckBox ID="lbl_IsActive" runat="server" OnCheckedChanged="chkIsActive_CheckedChanged" AutoPostBack="true" Checked='<%# Eval("IsActive") %>' ></asp:CheckBox>
My javascript
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.getElementById("<%=IsChecked.ClientID%>");
if (confirm("Do you want to save data?")) {
confirm_value.value = "1";
} else {
confirm_value.value = "0";
}
}
</script>
my C# code behind
protected void chkIsActive_CheckedChanged(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "Confirm();", true);
string confirmValue = IsChecked.Value;
if (confirmValue == "1")
{
string CarEstimateID = "";
Entities.CarEstimateFirms ObjEst = new Entities.CarEstimateFirms();
CheckBox chk = (CheckBox)sender;
GridViewRow gr = (GridViewRow)chk.Parent.Parent;
CarEstimateID = (GridView1.Rows[gr.RowIndex].FindControl("lbl_CarEstimateFirmID") as Label).Text; // GridView1.DataKeys[gr.RowIndex].Value.ToString();
ObjEst.CarEstimateFirmID = Convert.ToInt32(CarEstimateID);
ObjEst.IsActive = chk.Checked;
BLL.Common.UpdateCarEstimateFirms(ObjEst);
BindGridView();
}
}
Add onchange javascript event in your checkbox:
<asp:CheckBox ID="lbl_IsActive" runat="server" OnCheckedChanged="chkIsActive_CheckedChanged" AutoPostBack="true"
Checked='<%# Eval("IsActive") %>' onchange="javascript:return Confirm();" ></asp:CheckBox>
Your javascript confirm method should be like below:
<script type = "text/javascript">
function Confirm() {
if (confirm("Do you want to save data?")) {
return true;
} else {
return false;
}
}
</script>
And remove below line from chkIsActive_CheckedChanged event from code behind:
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "Confirm();", true);

If the validation of textbox fails it should be in same textbox and restrict user to move to another textbox

In the below code i have a javascript function and a textbox.The validations are working perfectly.My aim if the validation fails it should clear the textbox value and cursor should be in the same textbox it should not move to other controls.
JS:
function ValidateRegExp(txtInput, REGEXP) {
var mySplitResult = new Array();
mySplitResult = REGEXP.split("~~");
var iReturn = 0;
for (i = 0; i < mySplitResult.length - 1; i++) {
var re = new RegExp(mySplitResult[i]);
if (!txtInput.match(re)) {
iReturn = iReturn + 1;
}
}
if (iReturn > 0) {
alert("Failed...");
} else {
alert("Success...");
}
}
codebehind:
txtField.Attributes.Add("onblur", "javascript:ValidateRegExp(document.getElementById('" + txtField.ClientID + "').value, '" + hidRegExp.Value + "');");
I don't know why it is not working for me this works I have just created a simple example by taking 2 textboxes
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtField" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
and this is my script
<script type="text/javascript">
function validate() {
var txt = document.getElementById("txtField");
if (txt.value === "" || txt.value.length <= 1) {
txt.value = ''; // to clear the textbox value
txt.focus(); // focus on the textbox
}
}
</script>
This is in aspx.cs file
protected void Page_Load(object sender, EventArgs e)
{
txtField.Attributes.Add("onblur", "javascript:validate()");
}
On Leave event or the blur even of every control you can call the validate() function. There is a property that focuses on invalid input. so it will stuck to the textbox till the valid data is put.
http://jqueryvalidation.org/validate/

Categories