ASP.NET MVC Cascading DropDownLists Javascript Iss

2019-07-23 14:11发布

问题:

After reviewing many tutorials and various approaches to Cascading DropDownLists, I decided to create a ViewModel for my View and then populate my DropDownLists based on this post: MVC3 AJAX Cascading DropDownLists

The goal here is the most basic and covered in many tutorials, but I still can't get it quite right... to populate a City dropdown based on the value of a State dropdown.

EDIT:

Since posting this request for help, I discovered Firebug (yes, that's how new I am to doing any sort of programming), and I was able to determine that I am successfully calling my controller, and pulling the necessary data. I believe the problem is the second half of my JavaScript that returns the data to my View.

Here is my View:

    <label>STATE HERE:</label>
    @Html.DropDownListFor(x => x.States, Model.States, new { @class = "chzn-select", id = "stateID" })
    <br /><br />
    <label>CITY HERE:</label>
    @Html.DropDownListFor(x => x.Cities, Enumerable.Empty<SelectListItem>(), new { id = "cityID" })

Here is the JavaScript within my View, and somehow I'm not handling my results correctly once I get them:

$(function () {
    $("#stateID").change(function () {
        var stateId = $(this).val();
        // and send it as AJAX request to the newly created action 
        $.ajax({
            url: '@Url.Action("GetCities")',
            type: 'GET',
            data: { Id: stateId },
            cache: 'false',

            success: function (result) {
                var citySelect = $('#cityID');
                $(citySelect).empty();

                // when the AJAX succeeds refresh the ddl container with

                $.each(result, function (result) {
                    $(citySelect)
                    .append($('<option/>', { value: this.simpleCityID })
                    .text(this.cityFull));

                });
            },
            error: function (result) {
                alert('An Error has occurred');
            }
        });
    });
});

Here is my controller called by the JavaScript:

public JsonResult GetCities(int Id)
    {
        return Json(GetCitySelectList(Id), JsonRequestBehavior.AllowGet);
    }

    private SelectList GetCitySelectList(int Id)
    {
        var cities = simpleDB.simpleCity.Where(x => x.simpleStateId == Id).ToList();

        SelectList result = new SelectList(cities, "simpleCityId", "cityFull");
        return result;
    }

Here are my results from Firbug, which tell me I'm building and getting the data without issue, just not populating my DropDownList correctly:

[{"Selected":false,"Text":"Carmel","Value":"IN001"},{"Selected":false,"Text":"Fishers","Value":"IN002"}]

If anyone has any suggestions as to why the JavaScript fails to populate the dropdrown, please comment, thanks!

回答1:

I have done this several times with something like this:

Create a partial to popolate dropdown list. Name it DropDownList and put in Shared folder of Views

@model SelectList     
@Html.DropDownList("wahtever", Model)

Your create view should be something like this (skipped irrelevant parts)

<script type="text/javascript">
    $(function() {
        $("#StateId").change(function() {
            loadLevelTwo(this);
        });

        loadLevelTwo($("#StateId"));
    });

    function loadLevelTwo(selectList) {
        var selectedId = $(selectList).val();

        $.ajax({
            url: "@Url.Action("GetCities")",
            type: "GET",
            data: {stateId: selectedId},
            success: function (data) {
                $("#CityId").html($(data).html());
            },
            error: function (result) {
                alert("error occured");
            }
        });
    }
</script>

@Html.DropDownList("StateId")

<select id="CityId" name="CityId"></select>

Carefully note the Empty Select item for CityId and the call of loadLevelTwo at document.ready

And your controller should be like:

public ActionResult Create()
{
    ViewBag.StateId = new SelectList(GetAllCities(), "Id", "Name");
    return View();
}

public ActionResult GetCities(int stateId) {
    SelectList model = new SelectList(GetCitiesOfState(stateId), "Id", "Name");
    return PartialView("DropDownList", model);
}


回答2:

Thank you for your assistance,

It turns out that in my JavaScript below, I was attempting to directly reference the simpleCityID and cityFull fields associated with my data model:

$.each(result, function (result) {
                $(citySelect)
                .append($('<option/>', { value: this.simpleCityID })
                .text(this.cityFull));

Instead, I needed to keep it generic and inline with JavaScript standards of referencing Value and Text:

$.each(modelData, function (index, itemData) {
                select.append($('<option/>', {
                    value: itemData.Value,
                    text: itemData.Text