使用AJAX MVC 4填充DropDownList

Mar*_*eyn 15 c# ajax asp.net-mvc jquery

我有一个包含2 @ DropDownListFor的助手的视图:

    @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>
    }
Run Code Online (Sandbox Code Playgroud)

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

 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; }
}
Run Code Online (Sandbox Code Playgroud)

创建页面时会填充其中一个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);
        });
    });
Run Code Online (Sandbox Code Playgroud)

这是AJAX调用的Controller:

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

      return Content(String.Join("", lstCities));
  }
Run Code Online (Sandbox Code Playgroud)

到目前为止一切正常 - 当我在我的省DropDown中选择一个值时,javascript事件会触发,而Controller操作会将选择列表值返回到Cities DropDown,但问题是数据(格式为数据) Action返回不正确.我通过创建一个Paragraph元素并使用ajax调用的返回值更新它的文本来测试它,即:"System.Web.Mvc.SelectListItemSystem.Web.Mvc.SelectListItemSystem.Web.Mvc.Select ListItem"

*注意:我是ajax的新手,在学习Jquery和AJAX的过程中.

小智 33

你得到一组字符串的原因"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);
}
Run Code Online (Sandbox Code Playgroud)

然后在脚本(不知道为什么你已经修改了默认idid="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));
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

编辑

继OP的评论,如果数据库包含的表名Cities与字段IDName,则控制器方法会是这样的

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);
}
Run Code Online (Sandbox Code Playgroud)

并且创建选项的脚本将是

$.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));
});
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用,除了我必须使用:`cities.append($('<option> </ option>').text(item.Text).val(item.ID));` (11认同)

Már*_*lez 5

您可以尝试以下吗?

这是我几天前回答的帖子。字体:MVC 4形式的动态DropDownLists

您应该在省ddl的change事件中创建一个ajax调用。此电话将要求采取行动,并返回所选省份的城市。

$("province_dll").change(function(){
    $.ajax({
         url: 'getCitiesController/getCitiesAction',
         type: 'post',
         data: {
               provinceId: provinceIdVar
         }
    }).done(function(response){
         $("cities_dll").html(response);
    }); 
});
Run Code Online (Sandbox Code Playgroud)

在行动中:

[HttpPost]
public ActionResult getCicitesAction(int provinceId)
{
     var cities = db.cities.Where(a => a.provinceId == provinceId).Select(a => "<option value='" + a.cityId + "'>" + a.cityName + "'</option>'";

     return Content(String.Join("", cities));
}
Run Code Online (Sandbox Code Playgroud)