Andy Evans
Andy Evans

Reputation: 7176

JQuery AJAX MVC || Passing a comma delimited list of selected values from a multi-select list box into a controller action

I have a listbox (multi-select) in my web form that is populated from a web service via AJAX when the form loads. This works great!

<select multiple="multiple" size="8" id="categoryFamily" onchange="GetCCRCode()"></select>
<select multiple="multiple" size="8" id="category" onchange="GetCCRCode()"></select>

When select one or more entries, I execute the code below to pass (what I thought were the) values from the listbox above into the action of the controller using the code below.

function GetCCRCode() {
    $('#ccrCode').html('');
    var catfam = $('#categoryFamily').val();
    var cat = $('#category').val();

    $.ajax({
        type: "POST",
        url: "/Home/LoadCCRCode/",
        data: { 'catfam': catfam, 'cat': cat },
        success: function (results) {
            alert('success');
        },
        error: function () {
            alert('error');
        }
    });
}

The action in the controller is called but (see below)

    [AcceptVerbs("POST")]
    public string LoadCCRCode(string catfam, string cat)
    {
        return string.Empty;
    }

But the problem I'm having is that the input parameters that are passed in are null. So I added the following line of code to the GetCCRCode() JavaScript method.

alert(catFam);

The result is an alert box that shows a comma separated list as I would expect, but a null is still getting passed in.

Any thoughts?

Thanks!

Upvotes: 1

Views: 7593

Answers (2)

Baz1nga
Baz1nga

Reputation: 15579

there is a typo catfam and camfam

also change your js code to:

function GetCCRCode() {
    $('#ccrCode').html('');
    var catfam = $('#categoryFamily').val();
    var cat = $('#category').val();

    $.ajax({
        type: "POST",
        url: "/Home/LoadCCRCode/",
        data: { catfam: catfam.ToString(), cat: cat.ToString() },
        success: function (results) {
            alert('success');
        },
        error: function () {
            alert('error');
        }
    });
}

Notice I removed the single quotes in the json data..

Upvotes: 2

bfavaretto
bfavaretto

Reputation: 71939

Looks like you have a typo! You're passing catfam, but server-side you check for camfam.

I suggest you also inspect the POST request with Firebug, to make sure the values are being posted. If they are, that will confirm the problem is server-side.

Upvotes: 1

Related Questions