我正在尝试编写一个有两个下拉列表的 MVC 网页。第二个列表的内容取决于第一个列表中选择的内容。
似乎没有使用内置 MVC 函数来完成此操作的明确方法,因此我将不得不自己动手。然而,我不清楚获得我需要的所有功能的最佳方法...即“与网络表单相同”:)
我已经以类似于 这个
但是我不知道如何开发这个,以便如果有第一次绑定时第一个列表中的“selected”元素将流过以在页面加载时自动绑定第二个列表。
编辑:
需要明确的是,我能够将过滤列表绑定到第二个下拉列表。但是,如果我的模型包含第一个下拉列表的选择,则选择设置正确,但第二个下拉列表未填充。
(我是否必须声明我对 MVC 很陌生,而 Javascript 对我来说就像某种外星语言?)
Edit2:
我对这个问题思考得更多一些。
显然,我受到开发 Web 表单的时间的强烈影响,而且我还没有完全“了解”MVC。
我认为我确实有一些东西应该在我的模型中捕获(即,如果我已经有设置两个下拉列表的信息,那么我应该以某种方式在控制器中捕获它并构建预设的下拉列表。而不是尝试构建一个“ondatabound”类型方法并让视图调用该方法(这是我最初的意图)...现在我需要去弄清楚如何做到这一点:)
I am trying to write an MVC webpage that has two drop down lists. The content of the second list depends on what is selected in the first.
There does not seem to be a definitive way of doing this using built in MVC functions so I am going to have to roll my own. However I am not clear on the best way of getting all the functionality I require... which is "be the same as webforms" :)
I have created the dropdowns in a way similar to this
However I am not sure how to develop this so that if there is a 'selected' element in the first list when it is first bound this will flow through to automatically binding the second list on page load.
Edit:
Just to be clear I have the ability to bind the filtered list to the second dropdown. However if my Model contains a selection for the first dropdown the selection is set correctly but the second dropdown list does not fill.
(do I have to state I am newish to MVC and Javascript is like some alien language to me?)
Edit2:
I have thought about this a bit more.
Clearly I am strongly influenced by my time developing webforms and I don't quite 'get' MVC yet.
I think that really I have some things I should be catching in my model (ie if I already have the info to set the two dropdowns then I should in some way catch that in the controller and build the dropdowns pre set. Rather than trying to build an "ondatabound" type method and have the view call that (which was my initial intent)... Now I need to go and work out how to do that :)
发布评论
评论(3)
这个< /a> 是我发现的更好的实现之一。 此处也讨论了该问题。
This is one of the better implementations that I found. The question has also been discussed here.
您的任务包含 3 个子任务:
"GetList" 操作如果您使用默认路由表(或者您需要在自定义路由表中创建特殊记录),则应采用参数“id”并返回带有 ddl2 选项列表的部分视图(没有母版页),如下所示:
You task contains 3 subtasks:
<script type="text/javascript">
</script>
"GetList" action should take parameter "id" if you use default routes table (or you need to create special record at routes table with custom) and return partial view (without master page) with list of options for your ddl2, like this:
请参阅此 博客文章,用于在 ASP.NET MVC 中创建级联下拉列表,并具有可下载的源代码。
See this blog post for creating cascading dropdown lists in asp.net mvc with downloadable source code.