【发布时间】:2016-12-01 17:22:25
【问题描述】:
我正在使用 Visual Studio 2015,我的项目是 ASP.NET Web 应用程序。使用 Web 表单模板。
我无法从 jQuery ajax 调用 webmethod
这是我的网络表单 aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="EquipmentSubmitter.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "WebForm2.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
onclick="ShowCurrentTime()" />
</div>
</form>
</body>
</html>
这是我的 webform aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace EquipmentSubmitter
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
}
}
永远不会到达 webmethod 中的断点。
BundleConfig.cs 或其他任何地方有什么需要更改的吗?
【问题讨论】:
-
你能试试 'url: "WebForm2/GetCurrentTime"' 吗?你不应该需要 .aspx。
-
您的 ajax 调用中
data:的定义出现错误。data: {name: $("#txtUserName").val()} -
很遗憾,这些建议都不起作用
标签: jquery asp.net ajax webmethod