Run method c# into javascript

Excuse me a question, I have this method of C # asp.

protected void btnSave_Click (object sender, EventArgs e)

Anyone know how I can send you run into a script? It can be done?.

Upvotes: 0

Views: 67

Answers (2)

Dev Chotaliya
Dev Chotaliya

Reputation: 11

Yes that can be done. For that you have create function in .aspx.cs page the code which is fired on click on save button copy that code in function and then follow below step.

//Call cs method from Javascipt

__doPostBack('callSaveButtonClick');

if(Page.ispostback)
{
        if (Request.Form["__EVENTTARGET"] == "callSaveButtonClick")
        {
            //Call save button click function
        }
}

Upvotes: 1

Aftab Ahmed
Aftab Ahmed

Reputation: 1737

You need to make this C# Method as web Method then you can access it from javascript.

<script> 
   function savefile() 
   {
        var url = "WebForm1.aspx/btnSaveHandler";
        $.ajax({
            type: "POST",
            url: url,
            data: "", 
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(msg) {
                if (msg.d != null) {
                    alert("We returned: " + msg.d);
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
            }
        });
    };
</script>
<asp:Button ID="Button1" runat="server" Text="Save" OnClientClick="savefile()" />

Your code behind file will look like this

[WebMethod]
private void btnSaveHandler()
{
    Object.assignHandler((sender,e) => evHandler(sender,e));
}
public void btnSave_Click(Objectsender, EventArgs e)
{
   // Code goes here
}

Upvotes: 0

Related Questions