aspx codebehind中的Web方法没有被击中

时间:2017-09-07 15:04:47

标签: c# jquery asp.net webforms webmethod

我后面的代码中有WebMethod没有被点击。我搜索了很多,发现了很多像这样的问题。我已经尝试了所有我认为没有成功的建议。

IDE:Visual Studio 2017 框架:4.0 jQuery版本:3.1.1 项目类型:Webforms(是的,我想念我心爱的MVC,但这不是我的错!)

错误:

  

{"消息":"无效的Web服务调用,缺少参数值:   \ u0027id \ u0027""堆栈跟踪":"在   System.Web.Script.Services.WebServiceMethodData.CallMethod(对象   target,IDictionary 2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary 2个参数)\ r \ n at   System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext的   context,WebServiceMethodData methodData,IDictionary`2 rawParams)\ r \ n   在   System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext的   context,WebServiceMethodData   methodData)"" ExceptionType":" System.InvalidOperationException"}

正在调用的网址:GET http://localhost:65050/Default.aspx/Save?{" id":" chkEditable"," wasChecked":" on" }

当我点击两个复选框中的任何一个时,我在Chrome控制台上收到以下错误

  

GET   http://localhost:65050/Default.aspx/Save {%22id%22:%22chkEditable%22%22wasChecked%22:%器220n%22}?   500(内部服务器错误)jquery-3.1.1.min.js:4

这是我的aspx代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
Inherits="TesteWebMethod.Default" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>

<script src="Scripts/jquery-3.1.1.js"></script>
<script src="Scripts/jquery-3.1.1.min.js"></script>

<script>
    $(document).ready(function () {
        $('#chkVisible').change(function () {
            Save('chkVisible', $('#chkVisible').val());
        });

        $('#chkEditable').change(function () {
            Save('chkEditable', $('#chkEditable').val());
        });
    });

    function Save(_id, _state) {
        var pageUrl = '<%= ResolveUrl("~/Default.aspx")%>';
        var _data = { "id": _id, "wasChecked": _state };

        $.ajax({
            type: "GET",
            url: pageUrl + "/Save",
            data: JSON.stringify(_data),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: OnFailure
        });
    }

    function OnFailure(response) {
        console.log('falha');
        alert(response.d);
    }
    function OnSuccess(response) {
        console.log('sucesso');
        alert(response.d);
    }
</script>
</head>
<body>
<form id="form1" runat="server">
    <asp:CheckBox runat="server" AutoPostBack="false" ID="chkVisible" Text="Visivel" />
    <asp:CheckBox runat="server" AutoPostBack="false" ID="chkEditable" Text="Editavel" />
</form>

这是代码隐藏

using System;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;

namespace TesteWebMethod
{
public partial class Default : System.Web.UI.Page
{

    [WebMethod(true)]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public static string Save(string id, string wasChecked)
    {
        bool b = wasChecked == "on";

        string data = "Id " + (b ? "was checked" : "was unchecked");

        JavaScriptSerializer TheSerializer = new JavaScriptSerializer();

        var json = TheSerializer.Serialize(data);

        return json;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    }
}
}

我真的被困在这上面了。有人能告诉我我做错了吗?

2 个答案:

答案 0 :(得分:1)

我的回答是你调用的方法是一个GET方法,但是你传递的数据好像方法是POST方法一样。 Webforms不会从请求内容中获取参数,并且就像它们来自查询字符串一样。您在请求中包含的JSON数据需要在查询字符串中进行URL编码,或者该方法需要转换为POST方法以及AJAX调用。

答案 1 :(得分:1)

如果将对象设置为json属性,则不应对data对象进行字符串化.jquery将知道如何构建GET请求。

$.ajax({
    type: "GET",
    url: pageUrl + "/Save",
    data: {"id": _data.id, "wasChecked": "'" + _data.wasChecked + "'"},
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: OnSuccess,
    failure: OnFailure
});

请注意,我必须策划数据,将单引号添加到wasChecked属性,因为That's the way ASP knows that's a string,我认为这是一个糟糕的实现。

凯文说,POST会更好。它会

$.ajax({
    type: "POST",
    url: "WebMethodTest.aspx/Save",
    data: JSON.stringify({ "id": 2, "wasChecked": "test" }),
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

并且

[WebMethod(true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Save(string id, string wasChecked)
{
相关问题