Nove124
Nove124

Reputation: 233

How to pass id to MVC controller with Jquery and ajax [ASP.NET]

What am I doing wrong? The url option works correctly. Paragraph tag gives correct values (when not hidden).

here is my html code


 @foreach (var item in listTest)
        {
            <div id="pan" class="form-group panel panel-default">
                <p id="TestsId" class="hidden">@item.Id</p>
                <text>@item.Name</text>
                <text>@item.testTypeCategory.Category</text>
                <text>@item.testTypeName.Name</text>
                <text>@item.Price</text>
                <button class="btn btn-danger btn-cart" type="button" style="float:right">Add</button>
            </div>

js code

 $(document).ready(function () {
    $('.btn-cart').click(function () {
        var myId = $('#TestsId').val();
    $.ajax({
        type: 'POST',
        url: '@Url.Action("AddToList")',
        dataType: 'json',
        data: { id:  myId},
        success: function (data) {
            var items = '';
            $.each(data, function (i, item) {
                var rows = "<tr>"
                    + "<td class='nameT'>" + item.Name + "</td>"
                    + "<td class='priceT'>" + item.Price + "</td>"
                    + "</tr>";
                $('#testTable tbody').append(rows);
            });
        },
    });
    return false;
    }); 
}); 

and the controller action

    public JsonResult AddToList(int id)
    {
        cart.Add(_tests.GetAll().FirstOrDefault(j => j.Id == id));
        return Json(cart);
    }

The id in the controller is always 0

Upvotes: 1

Views: 3600

Answers (1)

Jon Ryan
Jon Ryan

Reputation: 1627

Like hikarunomemory says use .text() instead of val() as it’s a paragraph and not an input element.

Worth noting though that because it’s in a loop you will end up with multiple elements with the same Id. As such I would change it to look for a class as duplicate Ids are invalid markup, and use .closest() to make sure the right one is picked:

var myId = $(this).closest('.TestsId').text()

Upvotes: 2

Related Questions