asp.net 如何从 AJAX 传递参数到web方法?

vnzz0bqm  于 2023-01-22  发布在  .NET
关注(0)|答案(2)|浏览(105)

我正在从我的web方法执行更新操作。我正在做的是我的webForm1.aspx页面中有两个文本框。我正在尝试将这些文本框的值发布到web方法,以便我的更新操作可以运行。下面是我的代码:

var uval1 = $("#up_tb1").val();
var uval2 = $("#up_tb2").val();
function upbtnclicked() {
        alert('clicked');
        $.ajax({
            type: "POST",
            url: "WebForm1.aspx/updateData",
            data: '{val1:"' + uval1 + '",val2:"' + uval2 + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            error: OnErrorCall
        });

        function OnSuccess(response) {
            alert(response.d);
        }
        function OnErrorCall(response) { console.log(error); }
    }

我的更新过程运行良好,但当我把调试点放在我的web方法上并检查参数值时,它包含未定义的值,并且没有从文本框中获得正确的值。下面是我的代码隐藏代码。请帮助我。

[WebMethod]
    public static bool updateData(string val1,string val2)
    {
        var db = new dbDataContext();
        var query = (from e in db.Employees
                     where e.ID == up_id
                     select e).FirstOrDefault();
        query.EMP_FNAME = val1;
        query.EMP_MNAME = val2;
        db.SubmitChanges();
        return true;    
    }
ttcibm8c

ttcibm8c1#

var uval1 = $("#up_tb1").val();
var uval2 = $("#up_tb2").val();
function upbtnclicked() {
    alert('clicked');
    $.ajax({
        type: "POST",
        url: "WebForm1.aspx/updateData",
        data: {val1: uval1 ,val2: uval2 },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        error: OnErrorCall
    });

    function OnSuccess(response) {
        alert(response.d);
    }
    function OnErrorCall(response) { console.log(error); }
}

并且必须确保传递的参数必须与服务器端的webmethod参数匹配。

[WebMethod]
public static bool updateData(string val1,string val2)
{
    using (var db = new dbDataContext())
    {
        var query = (from e in db.Employees
                     where e.ID == up_id
                     select e).FirstOrDefault();
        query.EMP_FNAME = val1;
        query.EMP_MNAME = val2;
        db.SubmitChanges();
    }
    return true;    
}
pgvzfuti

pgvzfuti2#

你需要从 AJAX 的data参数中发送一个数组,尝试如下:

var uval1 = $("#up_tb1").val();
var uval2 = $("#up_tb2").val();
function upbtnclicked() {
        alert('clicked');
        $.ajax({
            type: "POST",
            url: "WebForm1.aspx/updateData",
            data: {val1: uval1 ,val2: uval2 },
            contentType: "application/json; charset=utf-8",
            success: OnSuccess,
            error: OnErrorCall
        });

        function OnSuccess(response) {
            alert(response.d);
        }
        function OnErrorCall(response) { console.log(error); }
    }

相关问题