Web方法不是在调用

问题描述 投票:-1回答:3

我在C#中使用Web方法,并通过Ajax调用该Web方法。但是没有调用web方法。

我需要使用带有c#方法的asp.net动态加载图表。所以我用web方法与客户端进行交互。请查看以下代码。我的网络方法没有打电话

Aspx Page:

<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowCurrentTime() {
    $.ajax({
        type: "POST",
        url: "CS.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 style = "font-family:Arial; font-size:10pt">
<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>

C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class _Default : 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();
}
}

得到“未定义”。需要你的帮助

c# webmethod
3个回答
1
投票

您从网页上将其称为POST,但在控制器上它是GET(这是默认值)

添加[HttpPost]属性来修复或更改对GET的ajax调用(可能更好)。


0
投票

jquery语法有问题。正确的语法应如下所示。请尝试以下更正的代码并告诉我们。

<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowCurrentTime() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/GetCurrentTime",
        data: {name: $("#<%=txtUserName.ClientID%>").val()},
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response);
        }
    });
}
function OnSuccess(response) {
    alert(response);
}
</script> 

-1
投票

你可以将这些行添加到web.config代码中,这些代码用于覆盖get和post协议:

 <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost"/>
  </protocols>
© www.soinside.com 2019 - 2024. All rights reserved.