Frage

I am developing an MVC 4 web application. One of the Razor views has two drop down lists. The first drop down list is populated by the ViewModel data which is passed to the view. The secondary drop down list is populated using a JQuery and Ajax call based on the selected ID from the first drop down list (cascading).

I have this working fine, however, whenever a user wishes to edit an existing record I can't get the selected secondary drop down list value to be selected.

This is my Razor code for the two drop down lists

<div class="lbl_a">
    Employer:
</div>
<div class="editor-field sepH_b">
     @Html.DropDownListFor(model => model.Employer, Model.EmployerList, "Select", new { @class = "inpt_a" })
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.DirectorateID, "Directorate/ Service Group")
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.DirectorateID, Model.DirectorateList, "Select")
</div>

This is my JQuery code

$(document).ready(function () {

//Pre load on page load
onEmployerChange();

//Hide and show DIVS based on selection
$("#Employer").change(onEmployerChange);

function onEmployerChange() {

        var dataPost = { orgID: val };
        $.ajax({
            type: "POST",
            url: '/User/GetDirectorates/',
            data: dataPost,
            dataType: "json",
            error: function () {
                alert("An error occurred." + val);
            },
            success: function (data) {
                var items = "";
                $.each(data, function (i, item) {
                    items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
                });

                $("#DirectorateID").html(items);
            }
        });

    }
}

});

When a user selects a value from the first drop down list, the selected ID is passed to the GetDirectorates action within the User Controller.

This is my GetDirectorates action which returns Json data

public ActionResult GetDirectorates(string orgID)
{
    if (String.IsNullOrWhiteSpace(orgID))
        orgID = "0";

    var Directorates = _ListService.GetListItemsByOrganisationID(Convert.ToInt32(orgID));

        List<SelectListItem> directorateList = new List<SelectListItem>();
        directorateList.Add(new SelectListItem() { Text = "Select", Value = "" });

        foreach (var directorate in Directorates)
        {
            directorateList.Add(new SelectListItem() { Text = directorate.description, Value = directorate.listItemID.ToString(), Selected = false });
        }

        return Json(new SelectList(directorateList, "Value", "Text"));
    }

Whenever the users wishes to edit an existing record I pass both the values for the first and second drop down list. Both drop down lists are populated with the proper data as expected, however, the selected value for the second drop down list is never selected.

This is a shortened version of the Edit action which the user calls when attempting to edit an existing record but shows the two drop down list selected values being passed.

public ActionResult EditNonMember(int id, string feedback, string courseDateID, string courseID)
{
    //code to retrieve data here

    vm.Employer = UserDetails.Employer;
    vm.DirectorateID = UserDetails.DirectorateID;

    return View(vm);
}

Would anyone be able to help me with this?

Thanks.

War es hilfreich?

Lösung

You need to get the directorate list for the saved employer id and set the DirectorateList collection and then the DirectorateID (from saved record);

public ActionResult EditNonMember(int id, string feedback, string courseDateID, 
                                                                 string courseID)
{
    //code to retrieve data here
    var userDetails=repositary.GetUserFromSomeId(id);
    vm.Employers=GetEmployers();
    vm.Employer = userDetails.Employer;
    vm.DirectorateList=GetDirectorateListForEmployer(userDetails.Employer);
    vm.DirectorateID = userDetails.DirectorateID;

    return View(vm);
}
private List<SelectListItem> GetEmployers()
{
  // to do : Return all employers here in List<SelectListItem>
}
private List<SelectListItem> GetDirectorateListForEmployer(int employerId)
{
  // to do : Return all Directorates for the selected employer 
}

Andere Tipps

This should do the trick:

var subSelect = $("#DirectorateID");
// clear the selection              
subSelect.empty();

//append each option to the list
$.each(data, function (i, item) {
    subSelect.append($('<option/>', {
                      value: item.Value,
                      text: item.Text
                  }));
});

Rather than setting it via the html method, I'm simply appending an option.

This is the method I use for cascading dropdown lists using ajax.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top