Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two dropdowns. One is populated with vehicle makes

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

The other one is empty and should be populated with vehicle models

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

This is my controller:

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

This is the AJAX call:

 <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

The dropdown is populated with 'undefined'. What am I doing wrong?

See Question&Answers more detail:os

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

1 Answer

Maybe this will help somebody. I am using two tables in my application. One is where I'm storing all the info I'm collecting from the form. The other one (Glossary) holds makes and models of vehicles. I have Models for both. Here is what I ended up doing.

Model Glossary:

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

This is what Makes look like in the table This is what Makes looks like

This is what Models of MBW (UniqueId == 3532) look like in the table enter image description here

Model Registration:

  [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

Registration Controller :

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

View:

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

This link was helpful: https://www.aspsnippets.com/Articles/ASPNet-MVC-jQuery-AJAX-and-JSON-Example.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...