将变量从jQuery传递到WebMethod(身份验证失败)

Pass variable from jQuery to WebMethod (Authentication failed)

本文关键字:WebMethod 身份验证 失败 变量 jQuery      更新时间:2023-09-26

我在VS2013中创建一个新的WebForms应用程序。我没有更改任何内容并创建了一个简单的页面。我想在用户单击按钮时在客户端加载此表

<table id="tblHelpRow">
        <thead>
            <tr class="title">
                <th>F2
                </th>
                <th>F3
                </th>
            </tr>
        </thead>
        <tbody id="helpRowBody">         
            <%=MyRow %>  
        </tbody>
    </table>
<asp:LinkButton ID="lnkEdit" runat="server" onclick="fnEdit();" />

这是我的脚本代码:

function fnEdit() {
    BindGridView();
};
function BindGridView() {
    rowid = {rowID:2};
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetRow",
            contentType: "application/json; charset=utf-8",
            data: param,
            dataType: "json",
            success: function (data) {
                 alert(data);
            }
        });
}

我的代码隐藏中有一个 WebMethod,存储结果为公共属性。数据源我存储在会话中,但行 ID 我需要从 jquery 传递。

        [WebMethod]
        public static string GetRow(int rowID)
        {
                DataTable dt = (DataTable)HttpContext.Current.Session["SourceData"];
                MyRow = "<tr>" +
                "<td>" + dt.Rows[rowID]["F2"].ToString() + "</td>" +
                "<td>" + dt.Rows[rowID]["F3"].ToString() + "</td>" +
                "</tr>";
            return "done";
    }

但我没有得到任何结果。当我成功放置中断时,我收到"身份验证失败"错误,并且此网络方法未执行。怎么了?我没有更改蚂蚁身份验证设置。

尝试删除 ScriptMethod 属性。您正在指定 POST 操作类型,但我相信脚本方法默认强制请求为 GET。另外,我相信您的参数需要是一个 JSON 字符串而不仅仅是一个整数:

var param = {rowID:2};
$.ajax({
    type: "POST",
    url: "Default.aspx/GetRow",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(param),
    dataType: "json",
    success: function (data) {
         alert(data);
    }
});

在我的VS2013 Web表单项目中,罪魁祸首是:

var settings = new FriendlyUrlSettings {AutoRedirectMode = RedirectMode.Permanent};

使用

FriendlyUruls 的默认设置解决了这个问题 - 不要使用 RedirectMode.Permanent。

像这样的 ajax 调用,其中数据参数很复杂。

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: applicationBaseUrl + "mypage.aspx/Calc",
        data: params     // data is json
    }).success(function (data, status, xhr) {
        //...
    }).error(function (xhr, status, error) {
        //...
    });

像这样的网络方法

   [WebMethod]
    public static string Calc(IEnumerable<AiApp> aiApps, Guid guid)
    { //...

使用

$.ajax({
        type: "POST",
        url: "Default.aspx/GetRow",
        contentType: "application/json; charset=utf-8",
        data: {rowID:2},
        dataType: "json",
        success: function (data) {
             alert(data);
        }
    });