简体   繁体   English

对ASP.NET MVC操作方法的JQuery Ajax调用-“内部服务器错误?”

[英]JQuery Ajax Call towards ASP.NET MVC action method - “Internal Server Error ?”

I have a simple action method that taking 2 parameter but when I call it by using jQuery Ajax in the Chrome Developer tool and Network tab > Xhr > Request status Code : 500 Internal Server error.... 我有一个简单的操作方法,采用2个参数,但是在Chrome开发者工具和“网络”标签>“ Xhr”>“请求状态代码:500内部服务器错误”中使用jQuery Ajax调用它时...

I am trying to find out the actual error but I can't get it? 我试图找出实际的错误,但我听不懂?

NOTE: when I throw a breakpoint at the actionMethod & when I click on a button the ajax call is issuing but during I can't get control and the breakpoint, so this means that the ajax call isn't reaching the action method as well. 注意:当我在actionMethod上抛出一个断点时,当我单击一个按钮时,会发出ajax调用,但是在此期间我无法获得控制权和该断点,因此这意味着ajax调用也无法到达action方法。

ActionMethod: ActionMethod:

[HttpPost]
public ActionResult LikePost(int userId, int entryId)
{
   return Content("User Id  Is  : " + userId + "Post Id  is : " + entryId);
}

jQuery: 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.");
   }
});

I am stuck for the last 2+ hours... The actual scenario is little different in my project but the problem I am facing is exactly this one. 在过去的两个多小时中,我陷入了困境……实际情况在我的项目中几乎没有什么不同,但是我所面临的问题正是这一情况。

You use method POST then you need use only one variable on your server side action. 您使用方法POST然后只需在服务器端操作中使用一个变量。

You can create a class like it: 您可以创建一个类似的类:

public class User
{
    public int UserId { get; set; }
    public int EntryId { get; set; }
}

After you need to change you MVC action: 在您需要更改MVC操作之后:

[HttpPost]
public ActionResult LikePost(User user)
{
    return Content("User Id  Is  : " + user.userId + "Post Id  is : " + user.entryId);
}

And send this data as JSON: 并以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.");
   }
});

When you submit data to the controller using Ajax, you can either use HttpPut or HttpPost annotations only. 使用Ajax向控制器提交数据时,只能使用HttpPut或HttpPost批注。 In both cases, at controller side you should use DTO (Data Transfer Object) as parameter. 在这两种情况下,在控制器端都应使用DTO(数据传输对象)作为参数。 So make a class (DTO Class) and your error will be gone. 因此,创建一个类(DTO类),您的错误将消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM