Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

asp.net mvc - Populating dropdown with JSON result - Cascading DropDown using MVC3, JQuery, Ajax, JSON

I've got a cascading drop-drown using mvc. Something like, if you select a country in the first-dropdown, the states of that country in the second one should be populated accordingly.

At the moment, all seems fine and I'm getting Json response (saw it using F12 tools), and it looks something like [{ "stateId":"01", "StateName": "arizona" } , { "stateId" : "02", "StateName":"California" }, etc..] ..

I'd like to know how to populate my second-dropdown with this data. My second drop-down's id is "StateID". Any help would be greatly appreciated.

Below is the code used to produce the JSON Response from the server:

[HttpPost]
public JsonResult GetStates(string CountryID)
{
    using (mdb)
    {
        var statesResults = from q in mdb.GetStates(CountryID)
                        select new Models.StatesDTO
                        {
                            StateID = q.StateID,
                            StateName = q.StateName
                        };

        locations.statesList = stateResults.ToList();
    }

    JsonResult result = new JsonResult();

    result.Data = locations.statesList;

    return result;
}

Below is the client-side HTML, my razor-code and my script. I want to write some code inside "success:" so that it populates the States dropdown with the JSON data.

<script type="text/javascript">
    $(function () {
        $("select#CountryID").change(function (evt) {

            if ($("select#CountryID").val() != "-1") {

                $.ajax({
                    url: "/Home/GetStates",
                    type: 'POST',
                    data: { CountryID: $("select#CountryID").val() },
                    success: function () { alert("Data retrieval successful"); },
                    error: function (xhr) { alert("Something seems Wrong"); }
                });
            }
        });
    });
</script> 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To begin with, inside a jQuery event handler function this refers to the element that triggered the event, so you can replace the additional calls to $("select#CountryID") with $(this). Though where possible you should access element properties directly, rather than using the jQuery functions, so you could simply do this.value rather than $(this).val() or $("select#CountryID").val().

Then, inside your AJAX calls success function, you need to create a series of <option> elements. That can be done using the base jQuery() function (or $() for short). That would look something like this:

$.ajax({
    success: function(states) {
        // states is your JSON array
        var $select = $('#StateID');
        $.each(states, function(i, state) {
            $('<option>', {
                value: state.stateId
            }).html(state.StateName).appendTo($select);
        });
    }
});

Here's a jsFiddle demo.

Relevant jQuery docs:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...