Luke Rayner Luke Rayner - 1 month ago 14
jQuery Question

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.

Answer

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);
        });
})