Rehan Shah
Rehan Shah

Reputation: 1627

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....

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:

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

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.

Upvotes: 0

Views: 602

Answers (2)

muhammad usman
muhammad usman

Reputation: 37

When you submit data to the controller using Ajax, you can either use HttpPut or HttpPost annotations only. In both cases, at controller side you should use DTO (Data Transfer Object) as parameter. So make a class (DTO Class) and your error will be gone.

Upvotes: 1

Alexander I.
Alexander I.

Reputation: 2714

You use method POST then you need use only one variable on your server side action.

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:

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

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

Upvotes: 2

Related Questions