一直在尝试为正确的输入和服务器验证进行 jquery 验证,以检查用户/电子邮件是否存在。唯一的问题是,即使通过了 jquery 验证,由于某种原因,参数并不总是从客户端发送。尝试在服务器端方法的开头输入断点,很少进入那里,将数据插入参数后发出警报并看到json看起来不错。我正在使用 Jquery、asp.net、c#。
客户端代码:
var user = $("#txt_register_username").val();
var password = $("#txt_register_password").val();
var firstname = $("#txt_register_firstname").val();
var lastname = $("#txt_register_lastname").val();
var birthdate = $("#txt_register_birthdate").val();
var picture = $("#txt_register_picture").val();
var car = $("#txt_register_car").val();
var email = $("#txt_register_email").val();
var home = $("#txt_register_home").val();
var cell = $("#txt_register_cell").val();
var params = "{username:" + user
+ ",firstname:" + firstname
+ ",lastname:" + lastname
+ ",birthdate:" + birthdate
+ ",pic:123"
+ ",carowned:" + car
+ ",email:" + email
+ ",password:" + password
+ ",home:" + home
+ ",cell:" + cell
+ "}";
$.ajax
({
type: "POST",
url: "Register.aspx/AddUser",
data: params,
contentType: "application/json; charset=utf-8",
dateType: "json",
success: function (result) {
alert(result.d);
}
});
图片稍后将是二进制的,所以它只是暂时的,忽略它是字符串。
服务器代码:
[WebMethod]
public static string AddUser(string username, string firstname, string lastname, string birthdate, string pic, string carowned, string email, string password, string home, string cell)
{
DataSet1TableAdapters.UsersTableAdapter userAdapter = new DataSet1TableAdapters.UsersTableAdapter();
DataSet1.UsersDataTable userTable = new DataSet1.UsersDataTable();
userAdapter.Fill(userTable);
int index = 0;
Console.WriteLine("entering valiation area");
foreach (DataRow dr in userTable.Rows)
{
if (userTable.Rows[index]["username"].Equals(username))
{
Console.WriteLine("a user who already exists tried to create an account");
return "user already exists with that username";
}
if (userTable.Rows[index]["email"].Equals(email))
{
Console.WriteLine("a user who already exists with an email tried to create an account");
return "user already exists with that email";
}
index++;
}
try
{
userAdapter.Insert(username, firstname, lastname, birthdate, pic, carowned, email, password, home, cell);
Console.WriteLine("new user added to db");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return "oops , something went wrong.";
}
return "new user added to database.";
}