简体   繁体   中英

Call WebMethod in C# codebehind without using a server form in ASPX page

Due to issues with styling, and needing multiple forms on one single web page, I currently have a form that is outside of the normal form with runat=server.

Is it possible for me to still call a WebMethod in the C# codebehind of this web page using ajax? I want to submit the information from this form to the same connection string that I am using earlier in the page, in a different form.

Here is my current code:

$().ready(function () {
    $("input[type=submit]").click(function () {
        handleClick();
        createJob();
    });
});

function createJob() {
var txtTestValue = document.getElementById('jobTitle').value;

$.ajax({
    // POST signals a data request
    type: "POST",
    // This directs which function in the c# code behind to use
    url: "Account/help.aspx/CreateJob",
    // The paramater pageIndex, page number we need to load, to pass to GetCustomers(int pageIndex)
    data: txtTestValue,
    // Type of data we are sending to the server (i.e. the pageIndex paramater)
    contentType: "application/json; charset=utf-8",
    // Type of data we expect back from the server (to fill into the html ultimately)
    dataType: "text",
    // If all goes smoothly to here, run the function that fills our html table
    success: OnSuccess,
    // On failure, error alert user (aka me so that I know something isn't working)
    failure: function (response) {
        alert("failure");
    },
    error: function (response) {
        alert("error");
    }
});
});

And my WebMethod in the codebehind:

[WebMethod]
public string CreateJob()
{
    //rest of my database code here
}

Sorry for the confusion but it's doing everything right up until the ajax code, and then seems to ignore it (and returns that the ajax failed with an error). My code is not reaching the WebMethod and any breakpoints I set in Visual Studio are not triggered in the page header. Thanks in advance for your help!

You need to declare the method as static .

[WebMethod]
public static string CreateJob()
       ^^^^^
{
    //rest of my database code here
}

Another issue is if input[type=submit] is ASP.Net Button control, it will post back to server. You cannot use ASP.Net Server control to make jQuery Ajax call - $.ajax.

// This code won't work if `input[type=submit]` is a server button control
$(function () {
    $("input[type=submit]").click(function () {
        handleClick();
        createJob();
    });
});

you need to use regular html input or button control with type=button instead of type=submit .

The webmethod should be static.

[WebMethod]
public static string CreateJob()
{
    //rest of my database code here
}

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