Akash Patel
Akash Patel

Reputation: 339

Passing parameters in Ajax post back in MVC

I am trying to pass ID parameter from a view to a controller on a click delete link available on a selected row.

Simplified View Layout

    @using (Html.BeginForm("#", "Schedule", FormMethod.Post, htmlAttributes: new { @class = "floating-labels" }))
    {
    @Html.AntiForgeryToken()

   <a href="#" onclick="DeleteSchedule(1);">Delete</a>
    }

JavaScript

<script type="text/javascript">
    function DeleteSchedule(id) {
        if (confirm('Are you sure you want to delete this Schedule?')) {
            $.ajax({
                type: "POST",
                url: '@Url.Action("Delete", "Schedule", new { id = "id" })',
                contentType: "application/json",
                data: { id },
                async: true,
                cache: false,
                success: function (result) { success(result); }
            });
        }
        return false;
    }

    function success(result) {
        $("#ScheduleList").html(result);
    }
</script>

Controller

namespace Controllers
{
    public class ScheduleController
    {
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id)
        {
            //do stuff
        }
    }
}

But on the click of a delete link I get below error and code does not hit controller action.enter image description here

I am not able to figure out what mistake I am making...

Upvotes: 2

Views: 2605

Answers (6)

Nicola
Nicola

Reputation: 61

try this, it solve the error on routing (different url Action) and the parameter on the controller: JavaScript

<script type="text/javascript">
function DeleteSchedule(id) {
    if (confirm('Are you sure you want to delete this Schedule?')) {
        $.ajax({
            type: "POST",
            url: '@Url.Action("Delete", "Schedule")',
            data: "id=" + id ,
            async: true,
            cache: false,
            success: function (result) { success(result); }
        });
    }
    return false;
}

function success(result) {
    $("#ScheduleList").html(result);
}
</script>

Controller:

 [HttpPost]
 [ValidateAntiForgeryToken]
   public ActionResult Delete(string id)
    {
      //do stuff
    }

Nicola.

Upvotes: 0

Badar Khalil
Badar Khalil

Reputation: 134

It is because you are not actullay posting the form pass it correctly and add _token in the ajax data list and value for that token will come from @Html.AntiforgeryToken()

Upvotes: 2

Wayne Davis
Wayne Davis

Reputation: 424

Here is my locally tested implementation that is working.

ScheduleController class:

    public class ScheduleController : Controller
    {
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Delete(int id)
        {
            return Ok(id);
        }        
    }

Page that sends the post request:


@Html.AntiForgeryToken()

<a href="#" onclick="DeleteSchedule(1);">Delete</a>

<div id="ScheduleList"></div>

<script>
    function DeleteSchedule(id) {       

        if (confirm('Are you sure you want to delete this Schedule?')) {
            var uri = '/Schedule/Delete?id=' + id;

            var tokenElement = document.getElementsByName('__RequestVerificationToken')[0];

            var data = {
                __RequestVerificationToken: tokenElement.value
            }

            $.ajax({
                type: "POST",
                url: uri,
                data: data,
                success: function (result) {
                    success(result);
                }
            });
        }
        return false;
    }

    function success(result) {
        $("#ScheduleList").html(result);
    }
</script>

The page does nothing but render the html, and the javascript handles the actual Ajax post. What I believe you were missing is the Validation token in your request.

Upvotes: 3

Rainer Llera
Rainer Llera

Reputation: 26

I think none of the answers above solve the issue. First of all I would replace your target url:

url: '@Url.Action("Delete", "Schedule", new { id = "id" })',

with

url: '@Url.Action("Delete", "Schedule", new { id = actualIdVariable })',

(replace "id" with the actual id variable from the model you're passing to the view). Note how your browser response is telling you that the url you're posting to is Schedule/Delete/id. That said, I'm not sure you even need the routeValues in this case (the new { id = ...} parameter). this is a POST action, and action parameters wouldn't come from route unless specified by by attribute routing (i.e. [Route("~/Schedule/Delete/{id}")] attribute on your action).

I think your post action is failing because it is trying to parse the "id" string as an int.

Second, I would change the data property of the ajax call and include the anti forgery token. Just because the anchor element you're binding the click event to, is inside the form with @Html.AntiforgeryToken() doesn't mean the generated token will be posted in the ajax request. You're not actually submitting/posting the form, you're just clicking a button.

it should be something like

data: { 
'id': id,
'__RequestVerificationToken': $('[name="__RequestVerificationToken"]').val()
}

Upvotes: 1

Pedro Ventura
Pedro Ventura

Reputation: 13

Try this, you are accesing a javascript variable on c# code, and you cant do that. If correct, please mark as answer.

function DeleteSchedule(id) {
        if (confirm('Are you sure you want to delete this Schedule?')) {
             var url = '@Url.Action("Delete", "Schedule")?id=' + id;
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: { id },
                async: true,
                cache: false,
                success: function (result) { success(result); }
            });
        }
        return false;
    }

Upvotes: 1

mahmed nabil
mahmed nabil

Reputation: 366

reading the error the request is most probably send correctly and there is an internal server error as mentioned in the 500 respond so please check the code that is inside the controller

Upvotes: 1

Related Questions