ASP.NET MVC 4 Allow User to Select State and then

2020-06-06 07:58发布

问题:

I have 3 Class and Tables

  1. State
  2. City
  3. Area

StateId is FK to City Table, CityId is FK to Area

On Create Form of Area I want to add State DropDown. I am sending State list in ViewBag, but don't know how to bind it. Also by default its bring all city with it, near about 100 plus I only want to bind city when state is changed, don't want model to bring all rows from city table when it first load.

Thanks in advance

回答1:

I recently blogged about cascading dropdownlists in MVC4 which I think is what you are after (although a little more detail would be appreciated).

http://jnye.co/Posts/12/creating-cascading-dropdownlists-using-mvc-4-and-jquery

In essence, in your controller:

public ActionResult Index()  
{  
    // These countries are equivalent to your states
    var states = new List<string> {"Ohio", "California", "Florida"};  
    var stateOptions = new SelectList(states);  
    ViewBag.States = stateOptions;  
    return View();  
}  

public JsonResult GetCities(string state)  
{  
    var cities = new List<string>();  
    switch (country)  
    {  
        case "Florida":  
            states.Add("City1");  
            states.Add("City2");  
            states.Add("City3");  
            break;  
        case "Ohio":  
            states.Add("City4");  
            states.Add("City5");  
            break;  
        case "California":  
            states.Add("City6");  
            states.Add("City7");  
            break;  
    }  
    //Add JsonRequest behavior to allow retrieving states over http get  
    return Json(cities, JsonRequestBehavior.AllowGet);  
}  

Then, in your view:

@using (Html.BeginForm())  
{  
    <div>Select state:</div>  
    <div>@Html.DropDownList("state",   
                            ViewBag.States as SelectList,   
                            "Please select",   
                            new { id = "state" })  
    </div>  
    <div>Select City:</div>  
    <div>  
        <select id="city" disabled="disabled"></select>  
    </div>  
    <input type="submit" value="Submit"/>  
}  

@section scripts{  
    <script type="text/javascript">  
        $(function() {  
            $('#state').on('change', function() {  
                var cityDropdown = $('#city');  
                //disable city drop down  
                cityDropdown.prop('disabled', 'disabled');  
                //clear drop down of old city
                cityDropdown.empty();  

                //retrieve selected state
                var state = $(this).val();  
                if (state.length > 0) {  
                    // retrieve data using a Url.Action() to construct url  
                    $.getJSON('@Url.Action("GetCities")', {  
                        state: state  
                    })  
                    .done(function (data) {  
                        //re-enable city drop down  
                        cityDropdown.removeProp('disabled');  
                        //for each returned state  
                        $.each(data, function (i, city) {  
                            //Create new option  
                            var option = $('<option />').html(city);  
                            //append city states drop down  
                            cityDropdown.append(option);  
                        });  
                    })  
                    .fail(function (jqxhr, textStatus, error) {  
                        var err = textStatus + ", " + error;  
                        console.log("Request Failed: " + err);  
                    });  
                }  
            });  
        })  
    </script>  
}