首页 > 解决方案 > JsonResult 的下拉菜单返回未定义

问题描述

我有两个下拉菜单。一个装有车辆制造商

<select id="vehicleMake" name="VehicleMake">
        @foreach (var item in Model.Cars)
        {
            if (@item.Category == 1072)
            {
                <option value="@item.UniqueId">@item.Description</option>
            }
        }
</select>

另一个是空的,应该用车辆模型填充

@Html.DropDownListFor(model => model.VehicleModel, Enumerable.Empty<SelectListItem>(), "Select your model", new {@id="vehicleModel" })

这是我的控制器:

  [HttpPost]
  public JsonResult GetVehicleModels(string vehicleMake)
  {
       var vehicleModels = db.Glossaries.Where(x => x.VehicleMakeId.Contains(vehicleMake)).Select(x => x.Description).Distinct().ToList();
       SelectList list = new SelectList(vehicleModels);

       return Json(new { Success = true, Result = list }, JsonRequestBehavior.AllowGet);
  }

这是 AJAX 调用:

 <script type="text/javascript">
        $("#vehicleMake").on('change', function () {
            alert($(this).val());
            $.ajax({
                type: "POST",
                url: "/Registration/GetVehicleModels",
                data: JSON.stringify({ 'vehicleMake': $(this).val() }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    result = $.parseJSON( results );
                    var toAppend = '';
                    $.each(result,function(i,o){
                        toAppend += '<option>' + o.Text + '</option>';
                    });

                     $('#vehicleModel').append(toAppend);                 
                },
                failure: function (response) {
                    alert("failure");
                },
                error: function (response) {
                    alert("error" + response.responseText);
                }
            });
        });
</script>

这是我在Chrome中的开发人员工具中获得的结果(选择“雪佛兰”时)

Success: true
Result: [{Disabled: false, Group: null, Selected: false, Text: "BROUGHAM", Value: null},…]
  0: {Disabled: false, Group: null, Selected: false, Text: "BROUGHAM", Value: null}
    Disabled: false
    Group: null
    Selected: false
    Text: "BROUGHAM"
    Value: null

下拉列表中填充了“未定义”。我究竟做错了什么?

标签: c#jqueryjsonajaxmodel-view-controller

解决方案


也许这会对某人有所帮助。我在我的应用程序中使用了两个表。一个是我存储从表单中收集的所有信息的地方。另一个(词汇表)包含车辆的品牌和型号。我有两个模型。这就是我最终要做的。

模型词汇表:

  public partial class Glossary
    {
      public int UniqueId { get; set; }
      public Nullable<int> Category { get; set; }
      public string Description { get; set; } //has both makes and models descriptions
      public string VehicleMakeId { get; set; } //has references of Make's UniqueId for Models. 
    }

这就是 Makes 在表格中的样子 这就是 Makes 的样子

这是 MBW 的型号(UniqueId == 3532)在表中的样子 在此处输入图像描述

型号注册:

  [DisplayName("Vehicle Make")]
  public string VehicleMake { get; set; }
  [DisplayName("Vehicle Model")]
  public string VehicleModel { get; set; }
  public List<SelectListItem> Glossary { get; set; } //referencing Glossary model in my view model

注册控制器:

//in public ActionResult Create()    
  IEnumerable<SelectListItem> CarMake = db.Glossaries.Where(x => x.Category == 1072).Select(x => new SelectListItem
  {
    Value = x.UniqueId.ToString(),
    Text = x.Description
  });
  ViewBag.VehicleMake = CarMake;

//Json:
  [HttpPost]
  public JsonResult GetVehicleModels(string VehicleMake)
  {
    var VehicleModelList = db.Glossaries.Where(m => m.VehicleMakeId == VehicleMake).Select(m => new
    {
      VehicleModelId = m.UniqueId,
      VehicleModelDescription = m.Description
    }).ToList();

     return Json(VehicleModelList, JsonRequestBehavior.AllowGet);
  }

看法:

  <div class="form-group">
    @Html.LabelFor(model => model.VehicleMake, htmlAttributes: new { @class = "control-label col-md-2 required" })
    <div class="col-md-10">
      @Html.DropDownListFor(model => model.VehicleMake, (IEnumerable<SelectListItem>)ViewBag.VehicleMake, new { @class = "form-control", required = "required" })
      @Html.ValidationMessageFor(model => model.VehicleMake, "", new { @class = "text-danger" })
    </div>
  </div>

  <div class="form-group">
    @Html.LabelFor(model => model.VehicleModel, htmlAttributes: new { @class = "control-label col-md-2 required" })
    <div class="col-md-10">
      @Html.DropDownListFor(model => model.VehicleModel, Enumerable.Empty<SelectListItem>(), "Select vehicle's make first", new { @id = "VehicleModel", @class = "form-control", required = "required" })
      @Html.ValidationMessageFor(model => model.VehicleModel, "", new { @class = "text-danger" })
    </div>
  </div>

  <script type="text/javascript">
    $("#VehicleMake").on('change', function () {
      $('#VehicleModel option').remove();

      $.ajax({
        type: "POST",
        url: "/Registration/GetVehicleModels",
        data: JSON.stringify({ 'vehicleMake': $(this).val() }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
          $.each(result, function (i, o) {
            $('#VehicleModel').append('<option value=' + o.VehicleModelId + '>' + o.VehicleModelDescription + '</option>');
          });
        },
        failure: function (response) {
          alert("Could not retrieve vehicle model list. ");
        },
        error: function (response) {
          alert("Something's not right... /n" + response.responseText);
        }
      });
    });
  </script>

此链接很有帮助:https ://www.aspsnippets.com/Articles/ASPNet-MVC-jQuery-AJAX-and-JSON-Example.aspx


推荐阅读