Andy Evans
Andy Evans

Reputation: 7176

MVC3 JQuery AJAX || Multiple passed parameters are null

I'm having some problems posting multiple parameters to my controller using AJAX. Both parameters end up null and can't figure out why. I'm trying to send the selected values from two drop down lists called "cat_fam_codes" and "cat_codes"

UPDATE: I've added the content type and data types listed below. Same problem: both parameters passed to the controller are null.

In the view:

    $('#cat_fam_codes').click(function () {
        var categoryData = {
            categoryFamilyCodes: $('#cat_fam_codes').val(),
            categoryCodes: $('#cat_codes').val()
        };

        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: '/EventReport/GetCCRCodes/',
            data: JSON.stringify(categoryData),
            success: function (jsonresults) {
                if (jsonresults != null) {
                    $('#ccr_codes').find('option').remove().end();
                    for (var i = 0; i < jsonresults.length; i++) {
                        $('#ccr_codes').append('<option value="' + jsonresults[i].CCRCodeId + '">' + jsonresults[i].Description + '</option>');
                    }
                }
            },
            error: function (xhr, status, error) {
                alert('Failed to retrieve CCR Codes for this list.  A "' + error + '" response was returned.');
            }
        });

    });

In the controller:

[HttpPost]
public ActionResult GetCCRCodes(string categoryFamilyCodes, string categoryCodes)
{ ... }

Both of the parameters that are passed into the controller a null. Any assisted would e greatly appreciated.

Thanks!

Upvotes: 1

Views: 2594

Answers (2)

counsellorben
counsellorben

Reputation: 10924

Check with Fiddler or a similar tool what is being returned to the controller via your $.ajax() call. It is possible that $.ajax is not sending the data in a form the JsonValueProviderFactory can deserialize. When I post JSON through $.ajax, I always explicitly specify the following options:

 contentType: "application/json; charset=utf-8",
 dataType: "json",

Upvotes: 2

archil
archil

Reputation: 39501

I would take simpler approach. Assuming you got those DropDownLists inside html form

$.post("/EventReport/GetCCRCodes/", $("form").serialize());

Upvotes: 2

Related Questions