Populate DropDownList using AJAX MVC 4

前端 未结 3 1709
星月不相逢
星月不相逢 2020-12-09 04:34

I have a view in place that contains 2 @DropDownListFor\'s Helpers:

    @using (Html.BeginForm(\"CreateOneWayTrip\", \"Trips\"))
    {
        @Html.Validati         


        
3条回答
  •  难免孤独
    2020-12-09 05:04

    The reason you are getting a colletion of strings "System.Web.Mvc.SelectListItemSystem" is that var lstCities = new SelectList(new[] { "City1", "City2", "City3" }); returns IEnumerable and String.Join("", lstCities) calls the .ToString() method of each SelectListItem item in the collection which returns "System.Web.Mvc.SelectListItemSystem" (not the value of the Text property of SelectListItem)

    The best way to populate the second dropdown list is to return json containing the collection of cities and update the DOM in the ajax success callback. There is no reason to create a SelectList - its just unnecessary extra overhead and you returning at least 3 times as much data back to the client as is necessary (the client has no concept of a C# SelectListItem class.

    public JsonResult FetchCities(int provinceId) // its a GET, not a POST
    {
        // In reality you will do a database query based on the value of provinceId, but based on the code you have shown
        var cities = new List() { "City1", "City2", "City3" });
        return Json(cities, JsonRequestBehavior.AllowGet);
    }
    

    Then in the script (not sure why you have modified the default id from id="StartPointProvince" to id="province_dll", but)

    var url = '@Url.Action("FetchCities", "Trips")'; // Don't hard code your url's!
    var cities = $('#city_dll'); // cache it
    $("#province_dll").change(function () {
        var id = $(this).val(); // Use $(this) so you don't traverse the DOM again
        $.getJSON(url, { provinceId: id }, function(response) {
            cities.empty(); // remove any existing options
            $.each(response, function(index, item) {
                cities.append($('').text(item));
            });
        });
    });
    

    Edit

    Further to OP's comments, if the database contained a table name Cities with fields ID and Name, then the controller method would be something like

    public JsonResult FetchCities(int provinceId) // its a GET, not a POST
    {
        var cities = db.Cities.Select(c => new
        {
          ID = c.ID,
          Text = c.Text
        }
        return Json(cities, JsonRequestBehavior.AllowGet);
    }
    

    and the script to create the options would be

    $.each(response, function(index, item) { // item is now an object containing properties ID and Text
        cities.append($('').text(item.Text).val(item.ID));
    });
    

提交回复
热议问题