小编典典

使用AJAX MVC 4填充DropDownList

ajax

我有一个包含2个@DropDownListFor的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>
    }

这是我用来捕获数据的临时模型:

 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; }
}

创建页面时将填充其中一个DropsDownList,而第二个将根据用户在第一个DropDownList中选择的选项进行填充。为了实现这一点,我正在使用ajax。我使用的javascript如下所示:

$("#province_dll").change(function () {

        $.ajax({

            url: 'getCities/Trips',

            type: 'post',

            data: {

                provinceId: $("#province_dll").val()

            }

        }).done(function (response) {

            $("cities_dll").html(response);

        });

    });

这是AJAX调用的Controller:

  [HttpPost]
  public ActionResult getCicites(int provinceId)
  {
      var lstCities = new SelectList(new[] { "City1", "City2", "City3" });

      return Content(String.Join("", lstCities));
  }

到目前为止,一切正常-当我在Province
DropDown中选择一个值时,将触发javascript事件,并且Controller操作确实将选择列表值返回给Cities
DropDown,但是问题是数据(数据格式)动作返回不正确。我通过创建一个Paragraph元素并使用ajax调用的返回值更新其文本来测试了这一点,该返回值是:“
System.Web.Mvc.SelectListItemSystem.Web.Mvc.SelectListItemSystem.Web.Mvc.SelectListListItem”

*注意:我是ajax的新手,正在学习Jquery和AJAX。


阅读 222

收藏
2020-07-26

共1个答案

小编典典

您获取字符串的原因"System.Web.Mvc.SelectListItemSystem"是,该方法var lstCities = new SelectList(new[] { "City1", "City2", "City3" });返回IEnumerable<SelectListItem>String.Join("", lstCities)调用返回的集合.ToString()中每个SelectListItem项目的方法"System.Web.Mvc.SelectListItemSystem"(而不是的Text属性值SelectListItem

填充第二个下拉列表的最佳方法是返回包含城市集合的json并更新ajax成功回调中的DOM。没有理由创建SelectList-它只是不必要的额外开销,并且您将至少3倍的数据返回给客户端(必要时,客户端没有C#SelectListItem类的概念)。

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);
}

然后在脚本中(不确定为什么将默认值id从修改id="StartPointProvince"id="province_dll",但是)

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));
        });
    });
});

编辑

除了OP的注释,如果数据库包含Cities带有字段ID和的表名Name,则controller方法将类似于

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);
}

和创建选项的脚本将是

$.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));
});
2020-07-26