![](/img/trans.png)
[英]ASP.NET MVC Action Call from Javascript AJAX Receives 500 Internal Server Error
[英]JQuery Ajax Call towards ASP.NET MVC action method - “Internal Server Error ?”
我有一個簡單的操作方法,采用2個參數,但是在Chrome開發者工具和“網絡”標簽>“ Xhr”>“請求狀態代碼:500內部服務器錯誤”中使用jQuery Ajax調用它時...
我試圖找出實際的錯誤,但我聽不懂?
注意:當我在actionMethod上拋出一個斷點時,當我單擊一個按鈕時,會發出ajax調用,但是在此期間我無法獲得控制權和該斷點,因此這意味着ajax調用也無法到達action方法。
ActionMethod:
[HttpPost]
public ActionResult LikePost(int userId, int entryId)
{
return Content("User Id Is : " + userId + "Post Id is : " + entryId);
}
jQuery的:
jQuery.ajax({
url: "@Url.Action("LikePost", "Home")",
method: "POST",
data: {
"userId": CurrentButton.attr("data-UserId"),
"entryId": CurrentButton.attr("data-entryId")
},
success: function () {
console.log("Succeded");
},
error: function () {
console.log("Failed.");
}
});
在過去的兩個多小時中,我陷入了困境……實際情況在我的項目中幾乎沒有什么不同,但是我所面臨的問題正是這一情況。
您使用方法POST
然后只需在服務器端操作中使用一個變量。
您可以創建一個類似的類:
public class User
{
public int UserId { get; set; }
public int EntryId { get; set; }
}
在您需要更改MVC操作之后:
[HttpPost]
public ActionResult LikePost(User user)
{
return Content("User Id Is : " + user.userId + "Post Id is : " + user.entryId);
}
並以JSON形式發送此數據:
var data = {
userId: CurrentButton.attr("data-UserId"),
entryId: CurrentButton.attr("data-entryId")
};
jQuery.ajax({
url: "@Url.Action("LikePost", "Home")",
method: "POST",
data: JSON.stringify(data),
success: function () {
console.log("Succeded");
},
error: function () {
console.log("Failed.");
}
});
使用Ajax向控制器提交數據時,只能使用HttpPut或HttpPost批注。 在這兩種情況下,在控制器端都應使用DTO(數據傳輸對象)作為參數。 因此,創建一個類(DTO類),您的錯誤將消失。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.