我正在通过我的网络方法执行更新操作。我正在做的是我的 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;
}
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;
}
您需要从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); }
}