G.AOUDIA
G.AOUDIA

Reputation: 15

AJAX receives 500 Internal server error when calling ASP.NET MVC Controller

I'am receiving a 500 internal server error when trying to call a controller action using Javascript AJAX.

I want to call a controller method when the user clicks the confirm button.

CS Controller

[HttpPost] 
[ValidateAntiForgeryToken]
public ActionResult Delete(string idFb, FormCollection from)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(urlAPISignature);
        var deleteTask = client.DeleteAsync("api/whitepages/" + idFb);
        deleteTask.Wait();
        var result = deleteTask.Result;
        if (result.IsSuccessStatusCode)
        {
            return RedirectToAction("Index");
        }
        return RedirectToAction("Index");
    }
}

CSHTML File

    columns.Add().Encoded(false).Sanitized(false).Titled("").Filterable(false).RenderValueAs(model =>
           "<img title=\"supprimer\" class=\"delBtnWp\" data-idEpi=\"" + model.IdFb + "\" src=\"" + @Url.Content("~/Content/Images/trash-can.png") + "\" height=\"24\" width=\"24\" alt=\"del\" />");
.
.
.
.
<script>
        $(".delBtnWp").click(function () {
            var idFb = $(this).attr("data-IdFb");
            bootbox.dialog({
                title: 'Confirmer la suppression',
                message: 'Souhaitez-vous vraiment supprimer la ligne ?',
                buttons: {
                    danger: {
                        label: 'Non'
                    },
                    success: {
                        label: 'Oui',
                        className: "btn-success",
                        callback: function () {
                            success ();
                        }
                    }
                },
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            type: 'POST',
                            url: "@Url.Action("Delete", "WhitePages")",
                            data: { IdFb: idFb },
                            success: function (data) {
                                alert("Yes");
                            }
                        });
                    }
                }
            });
        });
</script>

The compiler is not even reaching the controller action.

Upvotes: 0

Views: 2598

Answers (1)

Rahul Sharma
Rahul Sharma

Reputation: 8311

Regarding your case, Remove the [ValidateAntiForgeryToken] from your ActionMethod in your Controller, or generate a forgery token on your View and then send it in your AJAX call. Also you need to change data-idEpi to data-idFb. This would resolve your 500 Internal Server Error.

Upvotes: 1

Related Questions