Thought
Thought

Reputation: 5846

Passing arguments in jQuery post to a method in controller

In ASP.NET MVC I was using this script to call a method in controller:

<script>
$.ajax({
    url: '@Url.Action("getBookedByUser", "Home")',
    data: "2",
    dataType: "html",
    success: function (data) {
        $('#someElement').html(data); // add the returned html to the DOM

        console.log(data);
    },
});
</script>

and this is the method I call:

public async Task getBookedByUser(string id)
{
     BenchesService benchService = new BenchesService();
     List<Bench> obj = await benchService.getLastBenchByUser(id);

     userBench = obj.ElementAt(0);
}

My problem is that id in my controller method is null. It doesn't assume the value "2" as I intend.

Any idea why?

Upvotes: 1

Views: 45

Answers (1)

John H
John H

Reputation: 14655

You're almost there. You need to setup the JSON to include your id property:

$.ajax({
    url: '@Url.Action("getBookedByUser", "Home")',
    data: { id: '2' },
    dataType: "html",
    success: function (data) {
        $('#someElement').html(data); // add the returned html to the DOM

        console.log(data);
    },
 });

Upvotes: 2

Related Questions