如何选择另一个后@ Html.DropDownList填充@ Html.DropDownList [英] How to populate a @Html.DropDownList after selecting another @Html.DropDownList
问题描述
DropDownList的一些分类装,我需要填充另一个@ Html.DropDownList视一号下拉列表中选择的选项。
DropDownList with some Categories loaded and i need to populate another @Html.DropDownList depending on the option selected on the 1st dropdown.
这是code我用填充第一下拉列表:
This is the code I use to populate the 1st dropdown:
在控制器:
TecnicService ListCategory = new TecnicService();
IList<Category> resultCat = ListCategory.GetCategory();
List<SelectListItem> CatDropDown = new List<SelectListItem>();
foreach (Category in resultadoCat)
{
CatDropDown.Add(new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name.ToString()
});
}
在View:
@model APP.Models.DataViewModel
@using (Html.BeginForm("NewPol", "Tecnic", null, FormMethod.Post, new { id = "pol-data-form", @class = "form-horizontal" }))
{
<div class="control-group">
<label for="category" class="control-label">Category</label>
<div class="controls">
@Html.DropDownList("BasicData", Model.Category, new { @class= "required", name="category"})
</div>
</div>
<div class="control-group">
<label for="ram" class="control-label">Ram</label>
<div class="controls">
@Html.DropDownList() WHAT DO I DO HERE???????
</div>
</div>
.
.}
我通过它返回一个列表服务获取数据,现在我需要根据一号下拉菜单的选择来填充第二个下拉列表。
I get the data through a service which returns a List, now I need to populate the 2nd dropdown depending on the selection of the 1st dropdown.
推荐答案
您正在寻找所谓的级联下拉列表
您可以创建一个jQuery插件,将跟踪的变化,向服务器发送一个Ajax请求得到的数值为其他下拉:
You can create a jQuery plugin that will track the changes and send the server an ajax request to get the values for the other drop down:
(function ($) {
$.fn.cascade = function (options) {
var defaults = { };
var opts = $.extend(defaults, options);
return this.each(function () {
$(this).change(function () {
var selectedValue = $(this).val();
var params = { };
params[opts.paramName] = selectedValue;
$.getJSON(opts.url, params, function (items) {
opts.childSelect.empty();
$.each(items, function (index, item) {
opts.childSelect.append(
$('<option/>')
.attr('value', item.Id)
.text(item.Name)
);
});
});
});
});
};
})(jQuery);
,然后简单地连线起来:
And then simply wire it up:
$(function () {
$('#SelectedProvinceId').cascade({
url: '@Url.Action("Cities")',
paramName: 'provinceId',
childSelect: $('#SelectedCityId')
});
$('#SelectedCityId').cascade({
url: '@Url.Action("Suburbs")',
paramName: 'cityId',
childSelect: $('#SelectedSuburbId')
});
});
这是一个简单的谷歌搜索一些较来源:
Some more sources from a simple google search:
AJAX与MVC4 级联
的http://www.sidecreative.com/Blog/Entry/Cascading-dropdown-lists-with-MVC4-and-jQuery
的http://www.$c$cproject.com/Articles/258172/Simple-Implementation-of-MVC-Cascading-Ajax-Drop-D
这篇关于如何选择另一个后@ Html.DropDownList填充@ Html.DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!