Friday, 19 February 2021

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



from Passing parameters in Ajax post back in MVC

No comments:

Post a Comment