Call C# Function From JavaScript/JQuery In Asp.net webforms

前端 未结 5 1323
南旧
南旧 2021-01-19 06:33

So, i have an aspx page which looks like this:

<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"Default.aspx.cs\" Inherits=\"_Default\" %>
         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-19 07:12

    You can use __doPostBack from the script, and use the RaisePostBackEvent method in the code behind to perform your server-side logic. If you're looking to do a redirect, this would probably be the best way.

    EDIT

    If you're looking to do some validation in JavaScript when a button is clicked, use OnClientClick to perform your JavaScript validation, and return true if the validation succeeds.

    
    

    Your JavaScript validation:

    validateStuff = function(){
        var isValid = true;
        var txt = document.getElementById("<%=TextBox1.ClientID%>");
        if (txt.value.toLower() != "james"){
           isValid = false;
        }        
        return isValid;
    }
    

    If the validateStuff function returns true, a postback will occur and you can handle your save/update logic in the button click event:

    protected void Button1_Click(object sender, EventArgs e)
    {
        //save some stuff to the database
    
        string txtValue = TextBox1.Text.Trim();
    }
    

    In JavaScript:

    redirectToAnotherPage = function(){
        __doPostBack("<%=SomeServerControl.ClientID%>", "someArgument");
    }
    

    In the code-behind:

    protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
    {
        //call the RaisePostBack event 
        base.RaisePostBackEvent(source, eventArgument);
    
        Response.Redirect("anotherpage.aspx");
    }
    

    If all you're looking to do is bring the user to another page, you can also do this:

    redirectToAnotherPage = function(){
        window.location.href = "somepage.aspx";
    }
    

提交回复
热议问题