【问题标题】:Pass Selected Drop Down List Value to Controller Action and then Populate Another Drop Down List Based on Value将选定的下拉列表值传递给控制器​​操作,然后根据值填充另一个下拉列表
【发布时间】:2016-12-12 16:37:15
【问题描述】:

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

查看:

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

As you can see, the ViewBag for Models is initially empty, when a manufacturer is selected I want this ViewBag to be updated with all of the models that hold that manufacturer.

我觉得我已经很接近了,但不知道下一步该做什么,朝着正确的方向前进会很棒。我也不确定到目前为止我所做的是否完全正确,因此如果有人能发现我忽略的任何内容或任何关于如何改进我的代码的建议,我将不胜感激。

我希望这是有道理的,任何帮助表示赞赏,在此先感谢。

更新代码:

查看:

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

    }

【问题讨论】:

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


    【解决方案1】:

    您当前的代码正在使浏览器导航到其他操作方法。但理想情况下,您需要使用 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,其中包含供您参考的虚拟数据。

    【讨论】:

    • 我已经尝试过了,当我在下拉列表中更改制造商时,模型仍然是空白的。开发者控制台显示:Uncaught ReferenceError: $ is not defined, for the line: $(function(){.
    • 你有js错误吗? (检查浏览器控制台)是否对 GetModels 进行网络调用(再次检查浏览器控制台!)。还要确保删除对旧 PopulateModels 方法的调用。
    • 对不起,我不小心提交了没有错误的评论(现在添加在上面的评论中)。我在“GetModels”操作方法中添加了一个断点,它似乎并没有停在这里。感谢您迄今为止的帮助!
    • 你的意思是“它似乎没有停在这里”?您是否检查了浏览器网络选项卡?是在打异步电话吗?返回的响应是什么?
    • 抱歉,我的意思是代码执行不会在 GetModels 方法的断点处暂停。我使用的是 Chrome,打开了开发者工具,然后是“网络”标签,但我认为我什么都看不到?
    猜你喜欢
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多