gpt4 book ai didi

javascript - 在 C# 代码隐藏中调用 WebMethod,而无需在 ASPX 页面中使用服务器窗体

转载 作者:太空宇宙 更新时间:2023-11-03 23:04:45 24 4
gpt4 key购买 nike

由于样式问题,并且需要在一个网页上使用多个表单,我目前有一个不属于带有 runat=server 的正常表单的表单。

我是否仍可以使用 ajax 在此网页的 C# 代码隐藏中调用 WebMethod?我想以不同的形式将此表单中的信息提交到我在页面前面使用的相同连接字符串。

这是我当前的代码:

$().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");
}
});
});

还有我的 WebMethod 在代码隐藏中:

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

对于造成的困惑,我们深表歉意,但它一直在执行直到 ajax 代码的所有操作,然后似乎忽略了它(并返回 ajax 因错误而失败)。我的代码没有到达 WebMethod,我在 Visual Studio 中设置的任何断点都没有在页眉中触发。预先感谢您的帮助!

最佳答案

您需要将该方法声明为static

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

另一个问题是,如果 input[type=submit] 是 ASP.Net Button 控件,它将回传到服务器。 您不能使用 ASP.Net Server 控件进行 jQuery Ajax 调用 - $.ajax。

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

您需要使用常规 html inputbutton 控件和 type=button 而不是 type=submit

关于javascript - 在 C# 代码隐藏中调用 WebMethod,而无需在 ASPX 页面中使用服务器窗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41727994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com