Randy Minder
Randy Minder

Reputation: 48512

MVC - Cascading Dropdown Lists - How to get the selected value?

I have an MVC app with a View that has cascading dropdowns. I have the following Ajax call that retrieves data for the second dropdown, after the user has selected a value in the first dropdown:

function GetAutoModel(_manufacturerId) {

    var autoSellerListingId = document.getElementById("AutoSellerListingId").value;

    $.ajax({
        url: "/AutoSellerListing/GetAutoModel/",
        data: { manufacturerId: _manufacturerId, autoSellerListingId: autoSellerListingId },
        cache: false,
        type: "POST",
        success: function (data) {
            var markup = "<option value='0'>-- Select --</option>";
            for (var x = 0; x < data.length; x++) {
                markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
            }

            $('#ModelList').html(markup).show();
        },
        error: function (reponse) {
            alert("error : " + reponse);
        }
    });
}

The following controller code is called to feed the Ajax call data:

[HttpPost]
public ActionResult GetAutoModel(int manufacturerId, int autoSellerListingId)
{
    int modelId = 0;

    // Get all the models associated with the target manufacturer
    List<AutoModel> modelList = this._autoLogic.GetModelListByManufacturer(manufacturerId);

    // If this is an existing listing, get the auto model Id value the seller selected.
    if (autoSellerListingId > 0)
        modelId = this._systemLogic.GetItem<AutoSellerListing>(row => row.AutoSellerListingId == autoSellerListingId).AutoModel.AutoModelId;

    // Convert all the model data to a SelectList and return it
    SelectList returnList = new SelectList(modelList, "AutoModelId", "Description", modelId);

    return Json(returnList);
}

Notice the last parameter in the new SelectList() call in the controller code (modelId). This is what I want the selected value to be set to once the select object is created in the Ajax call. The problem is that I don't know how to access this value in the client. Everything is working correctly, I just don't know how to access the selected value, and then set it.

Upvotes: 0

Views: 553

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039268

The problem is that I don't know how to access this value in the client.

You could look at the Selected boolean property on the client:

if (data[x].Selected) {
    markup += "<option value=" + data[x].Value + " selected=\"selected\">" + data[x].Text + "</option>";
} else {
    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}

Upvotes: 2

Related Questions