JsonResult 的下拉菜单返回未定义

Posted

技术标签:

【中文标题】JsonResult 的下拉菜单返回未定义【英文标题】:Dropdown from JsonResult returns undefined 【发布时间】:2020-06-08 14:48:29 【问题描述】:

我有两个下拉菜单。一个是车辆品牌

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

This is the results I'm getting in Developer Tools in Chrome (when 'Chevrolet' is chosen)

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

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

【问题讨论】:

success 回调中,你有一个名为result 的参数,然后你解析一个名为results 的东西,据我所知,它在任何地方都没有定义。 @TKharaishvili 我停下来,它说:断点目前不会被击中。没有为此文档加载任何符号。 我添加了一条新评论,请看一下。 不,将 results 更改为 result 并没有改变任何东西。 尝试$.each(result.Result, ... result 参数,我认为,是具有SuccessResult 两个属性的参数,这意味着result.Result 是您要迭代的那个。 【参考方案1】:

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

模型词汇表:

  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. 
    

这就是 Make 在表格中的样子

这是 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

【讨论】:

以上是关于JsonResult 的下拉菜单返回未定义的主要内容,如果未能解决你的问题,请参考以下文章

尝试创建 CSS 下拉菜单时未定义接收“$”

下拉菜单的角度 6 自定义指令不起作用

MFC 在自定义工具栏上添加有下拉菜单的按钮。

制作二级下拉菜单

下拉菜单 KivyMD 未打开

下拉菜单未显示和导航未居中