通过AJAX传递参数,但在MVC方法中显示为空
本文关键字:方法 显示 MVC 但在 AJAX 参数 通过 | 更新日期: 2023-09-27 18:07:30
我新的MVC和我试图显示一个方法与AJAX。问题是,我传递给方法的参数显示为空,但当我调试ajax代码时,参数不是空的。我不知道我做错了什么。
这是我的c#方法 public JsonResult AllAccountList(int accountID)
{
Client myClient = new AccountServiceClient().GetClientByUsername(System.Web.HttpContext.Current.User.Identity.Name);
IEnumerable<Account> myAccounts = new AccountServiceClient().GetAccountWithClient(myClient.ClientID);
List<AccountModel> myList = new List<AccountModel>();
foreach (Account a in myAccounts.Where(a => a.AccountID == Convert.ToInt32(accountID)))
{
myList.Add(new AccountModel() { AccountID = a.AccountID,TypeID_FK = a.TypeID_FK, FriendlyName = a.FriendlyName, Currency = a.Currency, AvailableBalance = a.AvailableBalance});
}
return Json(myList, JsonRequestBehavior.AllowGet);
}
这是我的AJAX
function btnSelectClicked(AccountID) {
var params = '{"accountID":"' + AccountID + '"}';
$.ajax({
type: "POST",
url: "/Account/AllAccountList",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var gridview = "<table>";
gridview += "<tr><td id='titleCol'>AccountId</td><td id='titleCol'>Account Type</td><td id='titleCol'>Friendly Name</td><td id='titleCol'>Currency</td><td id='titleCol'>Available Balnce</td></tr>";
for (var i = 0; i < data.length; i++) {
gridview += "<tr><td>" + data[i].AccountID +
"</td><td>" + data[i].TypeID_FK +
"</td><td>" + data[i].FriendlyName +
"</td><td>" + data[i].Currency +
"</td><td>" + data[i].AvailableBalance + "</td></tr>";
}
gridview += "</table>";
$("#display2").html(gridview);
},
error: function (xhr,err) {
alert(xhr.responseText + "An error has occurred during processing your request.");
}
});
};
尝试更改
var params = '{"accountID":"' + AccountID + '"}';
var params = {accountID: AccountID };
看看是否有帮助
:我没想到会抱怨一个函数…当然,当我使用jquery ajax方法时,我会使用我需要的特定方法,而不是根ajax()方法。不妨试试这个
function btnSelectClicked(AccountID) {
var params = {accountID: AccountID };
$.post("/Account/AllAccountList", data, function(data) {
var gridview = "<table>";
gridview += "<tr><td id='titleCol'>AccountId</td><td id='titleCol'>Account Type</td><td id='titleCol'>Friendly Name</td><td id='titleCol'>Currency</td><td id='titleCol'>Available Balnce</td></tr>";
for (var i = 0; i < data.length; i++) {
gridview += "<tr><td>" + data[i].AccountID +
"</td><td>" + data[i].TypeID_FK +
"</td><td>" + data[i].FriendlyName +
"</td><td>" + data[i].Currency +
"</td><td>" + data[i].AvailableBalance + "</td></tr>";
}
gridview += "</table>";
$("#display2").html(gridview);
});
})
.fail(function(jqXHR, textStatus, errorThrown ){
alert(jqXHR.responseText + "An error has occurred during processing your request.");
});
};