简体   繁体   中英

Passing Jquery variable to MVC Controller using AJAX

I have a variable in Jquery which I want to pass to one of the parameters in my Controller method.

This is my AJAX code:

<script>
    $(document).on("click", ".getDetails", function (e) {
        var val = $(this).val();
        alert(val);
        $.ajax({
            url: '/Home/GetDetails',
            contentType: 'application/html; charset=utf-8',
            type: 'POST',
            data: {
                partsId: val
            },
            dataType: 'html'
        })
            .success(function (result) {
                $('#detailsPlace').html(result);
            })
            .error(function (xhr, status) {
                alert(status);
            });
    })
</script>

Here is my controller code:

public ActionResult GetDetails(int partsId)
{
    return PartialView();
}

All I want to do is pass the val variable to my partsId parameter, the code that I am currently using keeps returning the partsId parameter as null whenever I debug it.

why dont use json format?

$(document).on("click", ".getDetails", function (e) {
    var val = $(this).val();
    alert(val);
    $.ajax({
        url: '/Home/GetDetails',
        contentType: 'application/json',
        type: 'POST',
        data: JSON.stringify({"partsId": val}),
        dataType: 'json'
    })
        .success(function (result) {
            $('#detailsPlace').html(result);
        })
        .error(function (xhr, status) {
            alert(status);
        });
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM