简体   繁体   中英

How to prevent code behind function from being activated with js

The problem:

I have a form with a code behind function and i also make some js validtions and i don't want the code behind funciton to work if the js returns false. I have tried to use OnClientClick and return false at the end of the function but i didn't work.

aspx:

<asp:Button ID="Button1" runat="server" 
  CssClass="action-button" 
  OnClientClick="return updateValidation();"  
  OnClick="Button1_Click" Text="Update" />

Code Behind:

public partial class Update : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack && Session["user"] != null)
        {

            UserService us = new UserService();
            string id = Session["user"] as string;
            string selectQuery = "SELECT * FROM users WHERE ID = '" + id + "'";
            DataTable table = us.ExecuteDataTable(selectQuery);

            SignUpName.Value = table.Rows[0]["fName"] as string;
            SignUpLastName.Value = table.Rows[0]["lName"] as string;
            email.Value = table.Rows[0]["email"] as string;
            birthDate.Value = table.Rows[0]["birthDate"] as string;
            city.Value = table.Rows[0]["city"] as string;
            address.Value = table.Rows[0]["address"] as string;
            zipCode.Value = table.Rows[0]["zipcode"] as string;
            Password.Value = table.Rows[0]["userPassword"] as string;
        }

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        
            string id = Session["user"] as string;
            string fName = SignUpName.Value.ToString();
            string lName = SignUpLastName.Value.ToString();
            string UserbirthDate = birthDate.Value.ToString();
            string Usercity = city.Value.ToString();
            string UserAddress = address.Value.ToString();
            string UserZipCode = zipCode.Value.ToString();
            string UserEmail = email.Value.ToString();
            string userPassword = Password.Value.ToString();
            UserService us = new UserService();
            User u = new User(fName, lName, id, UserbirthDate, Usercity, UserAddress, UserZipCode, UserEmail, userPassword);

            us.UpdateUser(u);
        
    }
}

Javascript:

function updateValidation() {        

    window.check = true;
    checkFName();
    checkLName();
    checkEmail();
    checkBrithDate();
    checkCity();
    checkAddress();
    checkZipCode();
    checkPassword();

    return check;

}

I have already tried returning false at the end of the js at any case but it didn't work either.

The code is structured fine and your window.check variable has a boolean value but instead of that, you are returning a variable named check which I do not see declared or being modified anywhere in your code example. Which means, the check variable does not have a boolean value, rather it has undefined or null in it.

See:

function updateValidation() {
    window.check = true;
    checkFName();
    checkLName();
    checkEmail();
    checkBrithDate();
    checkCity();
    checkAddress();
    checkZipCode();
    checkPassword();
    // Instead of just returning check, return window.check
    return window.check;

}

If that does not work either, then it is certain that the boolean is always true which doesn't stop the post back.

Also, you can use jquery to bind the event which is my preferred way of binding the events:

<asp:Button ID="Button1" runat="server" 
  CssClass="action-button" 
  OnClick="Button1_Click" Text="Update" />

$(document).ready(function(){
    $('#<%= Button1.ClientID %>').on('click', function(){
        window.check = true;
        checkFName();
        checkLName();
        checkEmail();
        checkBrithDate();
        checkCity();
        checkAddress();
        checkZipCode();
        checkPassword();
        // Instead of returning check, return window.check
        return window.check;
    });
    // Your Javascript functions go here...
});

Notice, I have removed the OnClientClick event from the button markup, and have bound the event directly to the element which is better than returning the boolean value twice, one in the method itself and the second in the button markup.


UPDATE

I suspect that your window.check object is undefined. Which is why it is returning an undefined instead of a boolean value. I would recommend you to replace window.check with just a global variable check like below:

$(document).ready(function(){
    var check; // declare a variable named check in global scope to the click event
    $('#<%= Button1.ClientID %>').on('click', function(){
        check = true; // set the initial value
        checkFName();
        checkLName();
        checkEmail();
        checkBrithDate();
        checkCity();
        checkAddress();
        checkZipCode();
        checkPassword();
 
        return check; // return the variable check instead of window.check
    });
    // Your Javascript functions go here...
});

You should to call the function Button1_Click after the function updateValidaton. You can do it this way: In the button element, replace the Button1_Click with function myFunction (or ahatever you and it to be called). Then: function myFunction(){ if (updateValidation()) Button1_Click(); }

It will call the Button1_Click function only if the validation returns true.

Change the ASPX to the following (note the event passed to the JS function and removed return ):

<asp:Button ID="Button1" runat="server" 
  CssClass="action-button" 
  OnClientClick="updateValidation(event);"  
  OnClick="Button1_Click" Text="Update" />

If window.check is a global bool parameter then check it in the JS function and prevent the submit event (note the event ):

function updateValidation(event) {        

    window.check = true;
    checkFName();
    checkLName();
    checkEmail();
    checkBrithDate();
    checkCity();
    checkAddress();
    checkZipCode();
    checkPassword();

    if (window.check == false) {
        event.preventDefault();
    }

    return check;
}

Generally you should be using the built in WebForms validators to get this accomplished, you can read about it here: https://www.codemag.com/Article/0307101/Validating-Data-On-Web-Forms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM