将选定的下拉列表值传递给控制器​​操作,然后根据值填充另一个下拉列表

时间:2016-12-12 16:37:15

标签: jquery ajax asp.net-mvc asp.net-mvc-4

我正在尝试从列表中选择制造商,然后根据用户选择的制造商,填充模型列表。

查看:

<div class="form-group">
        @Html.LabelFor(model => model.Manufacturer.ManufacturerName, "Model",
            htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-5">
            @Html.DropDownList("ManufacturerID", (List<SelectListItem>)ViewBag.Manufacturers,
                htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Manufacturer.ManufacturerName, "",
                new { @class = "text-danger", onchange = "PopulateModels()" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Model.ModelName, "Model",
            htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-5">
            @Html.DropDownList("ModelID", (List<SelectListItem>)ViewBag.Models,
                htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Model.ModelName, "",
                new { @class = "text-danger" })
        </div>
    </div>

    <script>
         function PopulateModels()
         {
              var url = '@Html.Raw(Url.Action("GetModelList", "FaultController", new { manufacturer="ManufacturerID" }))';
              window.location = url;
         }
    </script>

控制器:

public List<SelectListItem> GetModelList(Manufacturer manufacturer)
    {
        List<SelectListItem> modelList = new List<SelectListItem>();

        var models = db.Models.Where(m => m.ManufacturerID == manufacturer.ManufacturerID);

        foreach (Model model in models)
        {
            modelList.Add(new SelectListItem
            {
                Text = model.ModelName,
                Value = model.ModelID.ToString()
            });
        }

        var sortedModelList = (from model in modelList
                               orderby model.Text
                               select model).ToList();

        return sortedModelList;
    }

public ActionResult Create(...)
    {
        .
        .
        .

        ViewBag.Models = new List<SelectListItem>();
        ViewBag.Manufacturers = GetManufacturerList();
    }

正如您所看到的,ViewBag for Models最初为空,当选择制造商时,我希望使用该制造商的所有模型更新ViewBag。

我觉得我已经接近但无法弄清楚接下来会发生什么,正确方向上的一点会很棒。我也不确定到目前为止我所做的事情是否完全正确,所以如果有人能发现任何我忽略的内容,或者对如何改进我的代码提出任何建议也将不胜感激。

我希望这是有道理的,感谢任何帮助,提前谢谢。

更新代码:

查看:

<div class="form-group">
        @Html.LabelFor(model => model.Manufacturer.ManufacturerName, "Model",
            htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-5">
            @Html.DropDownList("ManufacturerID", (List<SelectListItem>)ViewBag.Manufacturers,
                htmlAttributes: new { @class = "form-control" , @id= "Manufacturers" })
            @Html.ValidationMessageFor(model => model.Manufacturer.ManufacturerName, "",
                new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Model.ModelName, "Model",
            htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-5">
            @Html.DropDownList("ModelID", (List<SelectListItem>)ViewBag.Models,
                htmlAttributes: new { @class = "form-control" , @id = "Models"})
            @Html.ValidationMessageFor(model => model.Model.ModelName, "",
                new { @class = "text-danger" })
        </div>
    </div>

    <script type="text/javascript">
         $(function(){
          $("#Manufacturers").change(function(){
             var v= $(this).val();
             $("#Models").empty();
             $.getJSON("@Url.Action("GetModels","Fault")?id="+v,function(data){
                 $.each(data,function(a,b){
                   $("#Models").append('<option value="'+b.Value+'">'+b.Text+'</option>');
                 });
             });
          });

        });
    </script>

控制器:

public ActionResult GetModels(int id)
    {
        var models = db.Models.Where(m => m.ManufacturerID == id)
                       .Select(x => new SelectListItem
                       {
                           Value = x.ModelID.ToString(),
                           Text = x.ModelName
                       }).ToList();
        return Json(models, JsonRequestBehavior.AllowGet);

    }

1 个答案:

答案 0 :(得分:2)

您当前的代码正在使浏览器导航到其他操作方法。但理想情况下,您需要使用ajax获取此数据,并使用它为第二个下拉列表构建SELECT选项。

因此,为第一个dropdiwn设置一个更改事件处理程序。

$(function(){
  $("#ManufacturerID").change(function(){
     var v= $(this).val();
     $("#Models").empty();
     $.getJSON("@Url.Action("GetModels","YourControlleName")?id="+v,function(data){
         $.each(data,function(a,b){
           $("#Models").append('<option value="'+b.Value+'">'+b.Text+'</option>');
         });
     });
  }); 

});

现在您有一个GetModels操作方法,它接受Id参数中的制造商ID并返回相应的模型。

public ActionResult GetModels(int id)
{
   var models = db.Models.Where(m => m.ManufacturerID == id)
                  .Select(x=>new SelectListItem { Value=x.Id.ToString(),
                                                  Text=x.Name}).ToList();
   return Json(models,JsonRequestBehavior.AllowGet);

}

Here是一个有虚拟数据的工作dotnetfiddle,供您参考。