ASP.NET MVC - 级联下拉

时间:2022-02-13 08:04:33

I'm currently learning ASP.NET MVC and using Nhibernate.

我目前正在学习ASP.NET MVC并使用Nhibernate。

I would like to use Cascading Drop-Down Boxes. Has anyone managed to get cascading drop-down boxes working in MVC?

我想使用Cascading Drop-Down Boxes。有没有人设法在MVC中使用级联下拉框?

Updated: I have looked at the following website: link text and used method 1.

更新:我查看了以下网站:链接文本和使用的方法1。

Controller Code

控制器代码

        var makeList = new SelectList(makeRepository.ListMakes (), "Id", "make",1);
        ViewData["Makes"] = makeList;

        //// Create Models view data
        var modelList = new CascadingSelectList(modelRepository.ListModels (Convert.ToInt32(makeList.SelectedValue.ToString())), "ModelID","Id", "Name");
        ViewData["Models"] = modelList;

View Code

查看代码

<%= Html.DropDownList("--Select Make--","Makes")%>
<label for="Makes">Car Model:</label>    
<%= Html.CascadingDropDownList("Models", "Makes") %> 

The correct list of cars is listed when a Make with id of 1 is selected, but when I select a different make the model list is empty?

当选择了ID为1的Make时,会列出正确的汽车列表,但是当我选择其他品牌时,型号列表为空?

4 个解决方案

#1


8  

You may want to read this TIP.

您可能想要阅读此提示。

In this tip, Stephen Walter demonstrates three methods of creating cascading dropdown lists. First, he shows you how to alter the list of options displayed by one dropdown list when an option in another dropdown list changes. Second, he shows you how to expose the data for the dropdown lists through a controller action. Next, he shows you how to grab the data for the dropdown lists from web services.

在这篇技巧文章中,Stephen Walter演示了三种创建级联下拉列表的方法。首先,他向您展示了当另一个下拉列表中的选项发生更改时,如何更改一个下拉列表中显示的选项列表。其次,他向您展示了如何通过控制器操作公开下拉列表的数据。接下来,他向您展示了如何从Web服务中获取下拉列表的数据。

#2


4  

You might want to have a look at a post I made a couple of weeks ago on exactly this

你可能想看看我几周前发表的一篇文章

First we will need to setup the JsonResult controller action.

首先,我们需要设置JsonResult控制器操作。

/// <summary></summary>  
/// Get Models
/// <param name="makeID" />  
/// <returns></returns>  
public JsonResult GetModels(string id)  
{       
   JsonResult result = new JsonResult();       
   var filteredModels = from model in homeViewModel.Models
                        where model.MakeID.ToString() == id
                        select model;       result.Data = filteredModels.ToList();
   result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;    
   return result;  
} 

This method now gives us the ability to use the nifty $.getJSON jquery call. The signature for the call is as follows

这个方法现在让我们能够使用漂亮的$ .getJSON jquery调用。呼叫的签名如下

jQuery.getJSON( url, [ data ], [ callback(data, textStatus) ] )

Given that we have setup 2 Drop Down Lists, one for Makes and the other for Models, like so.

鉴于我们已经设置了2个下拉列表,一个用于制作,另一个用于模型,如此。

   Html.DropDownListFor((model) => model.MakeID, new SelectList(Model.Makes, "ID", "Description"))    
   Html.DropDownListFor((model) => model.ModelID, new SelectList(Model.Models, "ID", "Description"))

we can include the following bit of jquery

我们可以包括以下jquery

//Hook onto the MakeID list's onchange event  
$("#MakeID").change(function() {   
   //build the request url   
   var url = '<!--Url.Content("~/")-->' + 'Home/GetModels';

   //fire off the request, passing it the id which is the MakeID's selected item value   
   $.getJSON(url, { id: $("#MakeID").val() }, function(data) {    
      //Clear the Model list    
      $("#ModelID").empty();    
      //Foreach Model in the list, add a model option from the data returned    
      $.each(data, function(index, optionData) {       
         $("ModelID").append("<option value=" + optionData.ID +">"+ optionData.Description +"</option>"  );    
      });
   });  
}).change();

Sorry for the shameless plug :(

抱歉无耻的插头:(

#3


2  

I have created a jQuery plugin for this.

我为此创建了一个jQuery插件。

http://weblogs.asp.net/rajbk/archive/2010/05/20/cascadingdropdown-jquery-plugin-for-asp-net-mvc.aspx

http://weblogs.asp.net/rajbk/archive/2010/05/20/cascadingdropdown-jquery-plugin-for-asp-net-mvc.aspx

#4


1  

The Tip you are using: ASP.NET MVC Tip #41 – Create Cascading Dropdown Lists with Ajax from Stephen Walther was not done with MVC Realease 1.0

您正在使用的提示:ASP.NET MVC提示#41 - 使用来自Stephen Walther的Ajax创建级联下拉列表没有使用MVC Realease 1.0

As such, it works fine with the downloaded project (after fixing some small issues), but when the you try to incorporate into MVC Release 1.0 things break.

因此,它适用于下载的项目(在修复一些小问题之后),但是当你尝试合并到MVC Release 1.0中时,事情就会中断。

For example: in the downloaded project, the scripts are in the Content Folder, in Release 1.0, the scripts are in the Scripts folder.

例如:在下载的项目中,脚本位于内容文件夹中,在版本1.0中,脚本位于Scripts文件夹中。

Also some (if not all) of the *.js files in the release changed from the bets and CTPs. This may be a problem too.

此外,发行版中的一些(如果不是全部)* .js文件也改变了赌注和CTP。这也可能是个问题。

I downloaded his project (fixed a couple of minor issues), and it worked fine within that project (the *.js files).

我下载了他的项目(修复了一些小问题),它在该项目中运行良好(* .js文件)。

For Example: I Fixed the following:

例如:我修正了以下内容:

CHANGE: \Views\Home\index.aspx

更改:\ Views \ Home \ index.aspx

Car Make:

<%= Html.DropDownList("--Select Make--", "Makes") %>

TO: Car Make: <%= Html.DropDownList("Makes", (SelectList)ViewData["Makes"], "--Select Make--")%>

TO:Car Make:<%= Html.DropDownList(“制作”,(SelectList)ViewData [“制作”],“ - 选择制作 - ”)%>

So as you see, there are some issues.

如你所见,有一些问题。

These type problems with tutorials and blogs are abundant; everyone wants to be considered an "Expert" on new technology being released so they write tutorials on betas and CTPs. The result is that the "Expert" will have stuff that doesn't work with the final release.

教程和博客的这些类型问题很多;每个人都希望被视为正在发布的新技术的“专家”,因此他们会编写有关beta和CTP的教程。结果是“专家”将拥有与最终版本无关的内容。

What you need to find is a Professional that has posted tutorials. A Professional will ensure that their tutorials work. What I mean by a professional is a professional trainer in that area of technology.

您需要找到的是发布教程的专业人士。专业人员将确保他们的教程有效。我所说的专业人士是该技术领域的专业培训师。

Stephen Walther has one of the better blogs and a lot of good stuff, but remember that he is a Microsoift Evangelist. He authors books on MS technology so he needs to be active in the blog world so he puts some good stuff out on leading edge technology. This keeps him deemed as an expert so his books can sell.

斯蒂芬沃尔特有一个更好的博客和很多好东西,但请记住,他是一个微博客传播者。他撰写有关MS技术的书籍,因此他需要积极参与博客世界,因此他将一些优秀的东西放在了前沿技术上。这使他被视为专家,因此他的书可以出售。

Just remember, regardless of the "Expert", there will be inaccuracies in blogs/writings (based on betas and CTPs) when you try to use the information in a final release.

请记住,无论“专家”如何,当您尝试在最终版本中使用这些信息时,博客/文章(基于测试版和CTP)都会出现不准确之处。

#1


8  

You may want to read this TIP.

您可能想要阅读此提示。

In this tip, Stephen Walter demonstrates three methods of creating cascading dropdown lists. First, he shows you how to alter the list of options displayed by one dropdown list when an option in another dropdown list changes. Second, he shows you how to expose the data for the dropdown lists through a controller action. Next, he shows you how to grab the data for the dropdown lists from web services.

在这篇技巧文章中,Stephen Walter演示了三种创建级联下拉列表的方法。首先,他向您展示了当另一个下拉列表中的选项发生更改时,如何更改一个下拉列表中显示的选项列表。其次,他向您展示了如何通过控制器操作公开下拉列表的数据。接下来,他向您展示了如何从Web服务中获取下拉列表的数据。

#2


4  

You might want to have a look at a post I made a couple of weeks ago on exactly this

你可能想看看我几周前发表的一篇文章

First we will need to setup the JsonResult controller action.

首先,我们需要设置JsonResult控制器操作。

/// <summary></summary>  
/// Get Models
/// <param name="makeID" />  
/// <returns></returns>  
public JsonResult GetModels(string id)  
{       
   JsonResult result = new JsonResult();       
   var filteredModels = from model in homeViewModel.Models
                        where model.MakeID.ToString() == id
                        select model;       result.Data = filteredModels.ToList();
   result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;    
   return result;  
} 

This method now gives us the ability to use the nifty $.getJSON jquery call. The signature for the call is as follows

这个方法现在让我们能够使用漂亮的$ .getJSON jquery调用。呼叫的签名如下

jQuery.getJSON( url, [ data ], [ callback(data, textStatus) ] )

Given that we have setup 2 Drop Down Lists, one for Makes and the other for Models, like so.

鉴于我们已经设置了2个下拉列表,一个用于制作,另一个用于模型,如此。

   Html.DropDownListFor((model) => model.MakeID, new SelectList(Model.Makes, "ID", "Description"))    
   Html.DropDownListFor((model) => model.ModelID, new SelectList(Model.Models, "ID", "Description"))

we can include the following bit of jquery

我们可以包括以下jquery

//Hook onto the MakeID list's onchange event  
$("#MakeID").change(function() {   
   //build the request url   
   var url = '<!--Url.Content("~/")-->' + 'Home/GetModels';

   //fire off the request, passing it the id which is the MakeID's selected item value   
   $.getJSON(url, { id: $("#MakeID").val() }, function(data) {    
      //Clear the Model list    
      $("#ModelID").empty();    
      //Foreach Model in the list, add a model option from the data returned    
      $.each(data, function(index, optionData) {       
         $("ModelID").append("<option value=" + optionData.ID +">"+ optionData.Description +"</option>"  );    
      });
   });  
}).change();

Sorry for the shameless plug :(

抱歉无耻的插头:(

#3


2  

I have created a jQuery plugin for this.

我为此创建了一个jQuery插件。

http://weblogs.asp.net/rajbk/archive/2010/05/20/cascadingdropdown-jquery-plugin-for-asp-net-mvc.aspx

http://weblogs.asp.net/rajbk/archive/2010/05/20/cascadingdropdown-jquery-plugin-for-asp-net-mvc.aspx

#4


1  

The Tip you are using: ASP.NET MVC Tip #41 – Create Cascading Dropdown Lists with Ajax from Stephen Walther was not done with MVC Realease 1.0

您正在使用的提示:ASP.NET MVC提示#41 - 使用来自Stephen Walther的Ajax创建级联下拉列表没有使用MVC Realease 1.0

As such, it works fine with the downloaded project (after fixing some small issues), but when the you try to incorporate into MVC Release 1.0 things break.

因此,它适用于下载的项目(在修复一些小问题之后),但是当你尝试合并到MVC Release 1.0中时,事情就会中断。

For example: in the downloaded project, the scripts are in the Content Folder, in Release 1.0, the scripts are in the Scripts folder.

例如:在下载的项目中,脚本位于内容文件夹中,在版本1.0中,脚本位于Scripts文件夹中。

Also some (if not all) of the *.js files in the release changed from the bets and CTPs. This may be a problem too.

此外,发行版中的一些(如果不是全部)* .js文件也改变了赌注和CTP。这也可能是个问题。

I downloaded his project (fixed a couple of minor issues), and it worked fine within that project (the *.js files).

我下载了他的项目(修复了一些小问题),它在该项目中运行良好(* .js文件)。

For Example: I Fixed the following:

例如:我修正了以下内容:

CHANGE: \Views\Home\index.aspx

更改:\ Views \ Home \ index.aspx

Car Make:

<%= Html.DropDownList("--Select Make--", "Makes") %>

TO: Car Make: <%= Html.DropDownList("Makes", (SelectList)ViewData["Makes"], "--Select Make--")%>

TO:Car Make:<%= Html.DropDownList(“制作”,(SelectList)ViewData [“制作”],“ - 选择制作 - ”)%>

So as you see, there are some issues.

如你所见,有一些问题。

These type problems with tutorials and blogs are abundant; everyone wants to be considered an "Expert" on new technology being released so they write tutorials on betas and CTPs. The result is that the "Expert" will have stuff that doesn't work with the final release.

教程和博客的这些类型问题很多;每个人都希望被视为正在发布的新技术的“专家”,因此他们会编写有关beta和CTP的教程。结果是“专家”将拥有与最终版本无关的内容。

What you need to find is a Professional that has posted tutorials. A Professional will ensure that their tutorials work. What I mean by a professional is a professional trainer in that area of technology.

您需要找到的是发布教程的专业人士。专业人员将确保他们的教程有效。我所说的专业人士是该技术领域的专业培训师。

Stephen Walther has one of the better blogs and a lot of good stuff, but remember that he is a Microsoift Evangelist. He authors books on MS technology so he needs to be active in the blog world so he puts some good stuff out on leading edge technology. This keeps him deemed as an expert so his books can sell.

斯蒂芬沃尔特有一个更好的博客和很多好东西,但请记住,他是一个微博客传播者。他撰写有关MS技术的书籍,因此他需要积极参与博客世界,因此他将一些优秀的东西放在了前沿技术上。这使他被视为专家,因此他的书可以出售。

Just remember, regardless of the "Expert", there will be inaccuracies in blogs/writings (based on betas and CTPs) when you try to use the information in a final release.

请记住,无论“专家”如何,当您尝试在最终版本中使用这些信息时,博客/文章(基于测试版和CTP)都会出现不准确之处。