如何将参数从ajax传递给web方法?

时间:2016-02-04 09:52:30

标签: c# asp.net ajax

我正在从我的网络方法进行更新操作。我正在做的是我的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;    
    }

2 个答案:

答案 0 :(得分:0)

您需要从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); }
    }

答案 1 :(得分:0)

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;    
}