JBoom JBoom - 16 days ago 10
jQuery Question

MVC Ajax POST data to controller always null

I have a function that posts the value of a dropdown list using AJAX to a controller, which then returns data that is dependant on the value selected.

The issue is that is constantly returns nothing, I can see in Developer Tools that the value is getting posted as Form Data

{"PropertyType":"House"}


When debugging
PropertyType
is constantly
null
when the controller is fired but can't seem to see why.

AJAX

function PropertyStyleFilter() {

var propertyType = $('#PropertyType').val();

var Url = '@Url.Action("PropertyStyleFilter")';
//var Url = '/Case/CaseDetails/PropertyStyleFilter/' + PropertyType;
console.log("Property Type:" + PropertyType);

$.ajax({
url: Url,
data: JSON.stringify({ PropertyType: propertyType }),
type: 'POST',
success: function (data) {
$("#PropertyStyle").html(""); // clear before appending new list

$("#PropertyStyle").append($('<option></option>').val("").html("Select Property Style..."));
$.each(data, function (i, style) {
//console.log(i, site);
$("#PropertyStyle").append($('<option></option>').val(style.Value).html(style.Text));
});
if (PropertyType != null) {
$("#PropertyStyle").val(PropertyType);
}
},
error: function (__x, __h, __m) {
console.log('ajax returned error', __m, __x, __h);
}

});
}


Controller

[HttpPost]
public ActionResult PropertyStyleFilter(string PropertyType)
{
var StyleList = (from ps in efContext.PropertyStyles
join pt in efContext.PropertyTypes
on ps.PropertyTypeId equals pt.Id
where pt.TypeName == PropertyType
orderby ps.Id
select new SelectListItem
{
Value = ps.StyleName,
Text = ps.StyleName
});


return Json(StyleList, JsonRequestBehavior.AllowGet);

}

Answer

Try if this works

function PropertyStyleFilter() {

        var propertyType = $('#PropertyType').val();

        var Url = '@Url.Action("PropertyStyleFilter")';
        //var Url = '/Case/CaseDetails/PropertyStyleFilter/' + PropertyType;
        console.log("Property Type:" + PropertyType);

        $.ajax({
            url: Url,
    dataType: 'json',
            data: { PropertyType: propertyType },
            type: 'POST',
            success: function (data) {
                $("#PropertyStyle").html(""); // clear before appending new list

                $("#PropertyStyle").append($('<option></option>').val("").html("Select Property Style..."));
                $.each(data, function (i, style) {
                    //console.log(i, site);
                    $("#PropertyStyle").append($('<option></option>').val(style.Value).html(style.Text));
                });
                if (PropertyType != null) {
                    $("#PropertyStyle").val(PropertyType);
                }
            },
            error: function (__x, __h, __m) {
                console.log('ajax returned error', __m, __x, __h);
            }

        });
    }