我无法从 json 调用 C# 网络方法
本文关键字:网络 方法 调用 json | 更新日期: 2023-09-27 17:56:08
我似乎无法从javascript调用c#webmethod。似乎问题在于输入代码,并将参数传输到该方法。
C# 网络方法:
//a method that invokes authentication
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Login(string UserName, string Password)
{
string result = null;
JavaScriptSerializer jsonSer = new JavaScriptSerializer();
try
{
TblUser LoginUser = new TblUser();
bool ans = LoginUser.Login(UserName, Password);
result = jsonSer.Serialize(ans.ToString());
return result;
}
catch
{
result = jsonSer.Serialize("noUser");
return result;
}
}
JavaScript:
//a function that grabs username and password
function ClientSideLogin() {
var UserName = $('#_txtUsername').val();
var Password = $('#_txtPassword').val();
Login(UserName, Password);
}
//a function to authenticate from client side
function Login(_UserName, _Password) {
// build a datastring in JSON
// only a string type should be passed with paranthesis
$(function () {
$.ajax({ // ajax call starts
url: 'WebServices.asmx/Login', // server side method
data: '{UserName:' + '"' + _UserName + '"' + ',Password:' + '"' + _Password + '"' + '}', // the parameters sent to the server
type: 'POST',
dataType: 'JSON', // Choosing a JSON datatype
contentType: "application/json; charset=utf-8",
success: function (data) // Variable data contains the data we get from serverside
{
if (data.hasOwnProperty('d')) {
resutls = $.parseJSON(data.d); // parse the answer to json format
}
else {
resutls = $.parseJSON(data);
}
var resObj = document.getElementById('result');
resObj.innerHTML = resutls;
}, // end of success
error: function (e) { // handle code in case of error
alert("קרתה תקלה בשרת, אנא נסה שוב מאוחר יותר" + e.responseText);
} // end of error
}) // end of ajax call
});
}
在你的函数中,你有
function Login(_UserName, _Password) {
$(function () {
$.ajax({ // ...
尝试将其更改为简单
function Login(_UserName, _Password) {
$.ajax({ // ...
你不能单步执行 ajax 函数(这是它的异步位!),但你可以执行以下操作来帮助你调试:
function onSuccess(data) { ... }
...
$.ajax({
...
success: onSuccess,
...
});
错误也是如此。然后,您可以在这些函数中设置断点,它们将命中。