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
192 views
in Technique[技术] by (71.8m points)

c# - Populate DropDownList using AJAX MVC 4

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

    @using (Html.BeginForm("CreateOneWayTrip", "Trips"))
    {
        @Html.ValidationSummary(false);
        <fieldset>
            <legend>Enter Your Trip Details</legend>

            <label>Start Point</label>
            @Html.DropDownListFor(m => m.StartPointProvince, (SelectList)ViewBag.Provinces, new { @Id = "province_dll", @class = "form-control" })
            @Html.DropDownListFor(m => m.StartPointCity, (SelectList)ViewBag.Cities, new { @Id = "city_dll", @class = "form-control" })

            <p style="float: none; text-align: center;">
                <button type="submit" value="Create" class="btn btn-info btn-circle btn-lg">
                    <i class="fa fa-check"></i>
                </button>

                <button type="submit" value="Create" class="btn btn-warning btn-circle btn-lg">
                    <i class="fa fa-times"></i>
                </button>
            </p>
        </fieldset>
    }

Here is the temporary model I use to Capture data:

 public class CaptureCreateTrip
 {
    [Required]
    [Display(Name = "Trip ID")]
    public string TripID { get; set; }

    [Required]
    public string StartPointProvince { get; set; }

    [Required]
    public string StartPointCity { get; set; }
}

One of the DropsDownList's are populated when the page is created and the second will be populated based on the option that the user chooses in the first DropDownList. To achieve this, i am using ajax. The javascript to I use looks like this:

$("#province_dll").change(function () {
        $.ajax({
            url: 'getCities/Trips',
            type: 'post',
            data: {
                provinceId: $("#province_dll").val()
            }
        }).done(function (response) {
            $("cities_dll").html(response);
        });
    });
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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<SelectListItem> 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<string>() { "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($('<option></option>').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($('<option></option>').text(item.Text).val(item.ID));
});

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

...