asp.net-mvc MVC 3 Razor 视图中的级联下拉菜单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4458970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cascading drop-downs in MVC 3 Razor view
提问by ProfK
I am interested in how to implement cascading dropdown lists for addresses in a Razor view. My Site entity has a SuburbId property. Suburb has a CityId, and City has ProvinceId. I would like to display dropdowns for all of Suburb, City, and Province on the Site view, where e.g. the suburb dropdown will initially display "First select a City", and the City dropdown, "First select a province". On selecting a province, cities in the province are populated etc.
我对如何在 Razor 视图中为地址实现级联下拉列表感兴趣。我的站点实体有一个 SuburbId 属性。Suburb 有一个 CityId,City 有一个 ProvinceId。我想在站点视图中显示所有郊区、城市和省的下拉列表,例如郊区下拉列表最初将显示“首先选择一个城市”,而城市下拉列表将显示“首先选择一个省”。在选择一个省时,该省内的城市都会有人口等。
How can I achieve this? Where do I start?
我怎样才能做到这一点?我从哪里开始?
回答by Darin Dimitrov
Let's illustrate with an example. As always start with a model:
让我们用一个例子来说明。一如既往地从模型开始:
public class MyViewModel
{
public string SelectedProvinceId { get; set; }
public string SelectedCityId { get; set; }
public string SelectedSuburbId { get; set; }
public IEnumerable<Province> Provinces { get; set; }
}
public class Province
{
public string Id { get; set; }
public string Name { get; set; }
}
Next a controller:
接下来是控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// TODO: Fetch those from your repository
Provinces = Enumerable.Range(1, 10).Select(x => new Province
{
Id = (x + 1).ToString(),
Name = "Province " + x
})
};
return View(model);
}
public ActionResult Suburbs(int cityId)
{
// TODO: Fetch the suburbs from your repository based on the cityId
var suburbs = Enumerable.Range(1, 5).Select(x => new
{
Id = x,
Name = "suburb " + x
});
return Json(suburbs, JsonRequestBehavior.AllowGet);
}
public ActionResult Cities(int provinceId)
{
// TODO: Fetch the cities from your repository based on the provinceId
var cities = Enumerable.Range(1, 5).Select(x => new
{
Id = x,
Name = "city " + x
});
return Json(cities, JsonRequestBehavior.AllowGet);
}
}
And finally a view:
最后是一个观点:
@model SomeNs.Models.MyViewModel
@{
ViewBag.Title = "Home Page";
}
<script type="text/javascript" src="/scripts/jquery-1.4.4.js"></script>
<script type="text/javascript">
$(function () {
$('#SelectedProvinceId').change(function () {
var selectedProvinceId = $(this).val();
$.getJSON('@Url.Action("Cities")', { provinceId: selectedProvinceId }, function (cities) {
var citiesSelect = $('#SelectedCityId');
citiesSelect.empty();
$.each(cities, function (index, city) {
citiesSelect.append(
$('<option/>')
.attr('value', city.Id)
.text(city.Name)
);
});
});
});
$('#SelectedCityId').change(function () {
var selectedCityId = $(this).val();
$.getJSON('@Url.Action("Suburbs")', { cityId: selectedCityId }, function (suburbs) {
var suburbsSelect = $('#SelectedSuburbId');
suburbsSelect.empty();
$.each(suburbs, function (index, suburb) {
suburbsSelect.append(
$('<option/>')
.attr('value', suburb.Id)
.text(suburb.Name)
);
});
});
});
});
</script>
<div>
Province:
@Html.DropDownListFor(x => x.SelectedProvinceId, new SelectList(Model.Provinces, "Id", "Name"))
</div>
<div>
City:
@Html.DropDownListFor(x => x.SelectedCityId, Enumerable.Empty<SelectListItem>())
</div>
<div>
Suburb:
@Html.DropDownListFor(x => x.SelectedSuburbId, Enumerable.Empty<SelectListItem>())
</div>
As an improvement the javascript code could be shortened by writing a jquery plugin to avoid duplicating some parts.
作为改进,可以通过编写 jquery 插件来缩短 javascript 代码以避免重复某些部分。
UPDATE:
更新:
And talking about a plugin you could have something among the lines:
谈论一个插件,你可以在以下几行中找到一些东西:
(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')
});
});
回答by Kris
Thanks Darinfor your lead to the solution. It greatly helped me to arrive to the point. But as 'xxviktor' mentioned, I did got circular ref. error. To get rid of it, I've done this way.
感谢Darin为您提供解决方案。它极大地帮助我达到了这一点。但正如 'xxviktor' 所提到的,我确实得到了循环引用。错误。为了摆脱它,我已经这样做了。
public string GetCounties(int countryID)
{
List<County> objCounties = new List<County>();
var objResp = _mastRepo.GetCounties(countryID, ref objCounties);
var objRetC = from c in objCounties
select new SelectListItem
{
Text = c.Name,
Value = c.ID.ToString()
};
return new JavaScriptSerializer().Serialize(objRetC);
}
And to achieve auto cascading, I've slightly extended jQuery extension this way.
为了实现自动级联,我通过这种方式稍微扩展了 jQuery 扩展。
$('#ddlCountry').cascade({
url: '@Url.Action("GetCounties")',
paramName: 'countryID',
childSelect: $('#ddlState'),
childCascade: true
});
And the actual JS is using this parameter as below (inside JSON request).
实际的 JS 使用这个参数如下(在 JSON 请求中)。
// trigger child change
if (opts.childCascade) {
opts.childSelect.change();
}
Hope this helps someone with similar issue.
希望这可以帮助有类似问题的人。
回答by xxviktor
be aware, that this solution doesn't work directly with EF 4.0. It causes "A circular reference was detected while serializing..." error. Here are possible solutions http://blogs.telerik.com/atanaskorchev/posts/10-01-25/resolving_circular_references_when_binding_the_mvc_grid.aspx, I've used second one.
请注意,此解决方案不能直接与 EF 4.0 一起使用。它会导致“序列化时检测到循环引用...”错误。以下是可能的解决方案http://blogs.telerik.com/atanaskorchev/posts/10-01-25/resolving_circular_references_when_binding_the_mvc_grid.aspx,我使用了第二个。
回答by dweremeichik
To implement cascading drop down lists that support MVC's built in validation and binding, you will need to do something a little different than what is done in the other answers here.
要实现支持 MVC 内置验证和绑定的级联下拉列表,您需要做一些与此处其他答案中所做的事情略有不同的事情。
If your model has validation, this will support it. An excerpt from a model with validation:
如果您的模型有验证,这将支持它。来自具有验证的模型的摘录:
[Required]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public Guid cityId { get; set; }
In your controller you need to add a get method, so that your view will be able to get the relevant data later:
在您的控制器中,您需要添加一个 get 方法,以便您的视图稍后能够获取相关数据:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetData(Guid id)
{
var cityList = (from s in db.City where s.stateId == id select new { cityId = s.cityId, name = s.name });
//simply grabbing all of the cities that are in the selected state
return Json(cityList.ToList(), JsonRequestBehavior.AllowGet);
}
Now, to the View that I mentioned earlier:
现在,对于我之前提到的 View:
In your view you have two drop downs similar to this:
在您看来,您有两个与此类似的下拉菜单:
<div class="editor-label">
@Html.LabelFor(model => model.stateId, "State")
</div>
<div class="editor-field">
@Html.DropDownList("stateId", String.Empty)
@Html.ValidationMessageFor(model => model.stateId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.cityId, "City")
</div>
<div class="editor-field">
@*<select id="cityId"></select>*@
@Html.DropDownList("cityId", String.Empty)
@Html.ValidationMessageFor(model => model.cityId)
</div>
The content in the drop downs are bound by the controller, and are automatically populated. Note: in my experience removing this binding and relying on java script to populate the drop downs make you lose validation. Besides, the way we are binding here plays nice with validation, so there is no reason to change it.
下拉列表中的内容由控制器绑定,并自动填充。注意:根据我的经验,删除此绑定并依靠 java 脚本填充下拉列表会使您失去验证。此外,我们在这里绑定的方式很适合验证,所以没有理由改变它。
Now onto our jQuery plugin:
现在进入我们的 jQuery 插件:
(function ($) {
$.fn.cascade = function (secondaryDropDown, actionUrl, stringValueToCompare) {
primaryDropDown = this; //This doesn't necessarily need to be global
globalOptions = new Array(); //This doesn't necessarily need to be global
for (var i = 0; i < secondaryDropDown.options.length; i++) {
globalOptions.push(secondaryDropDown.options[i]);
}
$(primaryDropDown).change(function () {
if ($(primaryDropDown).val() != "") {
$(secondaryDropDown).prop('disabled', false); //Enable the second dropdown if we have an acceptable value
$.ajax({
url: actionUrl,
type: 'GET',
cache: false,
data: { id: $(primaryDropDown).val() },
success: function (result) {
$(secondaryDropDown).empty() //Empty the dropdown so we can re-populate it
var dynamicData = new Array();
for (count = 0; count < result.length; count++) {
dynamicData.push(result[count][stringValueToCompare]);
}
//allow the empty option so the second dropdown will not look odd when empty
dynamicData.push(globalOptions[0].value);
for (var i = 0; i < dynamicData.length; i++) {
for (var j = 0; j < globalOptions.length; j++) {
if (dynamicData[i] == globalOptions[j].value) {
$(secondaryDropDown).append(globalOptions[j]);
break;
}
}
}
},
dataType: 'json',
error: function () { console.log("Error retrieving cascading dropdown data from " + actionUrl); }
});
}
else {
$(secondaryDropDown).prop('disabled', true);
}
secondaryDropDown.selectedindex = 0; //this prevents a previous selection from sticking
});
$(primaryDropDown).change();
};
} (jQuery));
You can copy the above jQuery that i created, into <script>...</script>
tags in your view, or in a separate script file if you wish (note I updated this to make it cross browser, however the scenario in which i was using is no longer required, it should work however).
<script>...</script>
如果您愿意,您可以将我创建的上述 jQuery 复制到视图中的标签中,或者复制到单独的脚本文件中(注意我更新了它以使其跨浏览器,但是不再需要我使用的场景,它但是应该可以工作)。
In those same script tags, (not in a separate file) you can call the plugin by using the following javascript:
在这些相同的脚本标签中,(不在单独的文件中)您可以使用以下 javascript 调用插件:
$(document).ready(function () {
var primaryDropDown = document.getElementById('stateId');
var secondaryDropdown = document.getElementById('cityId');
var actionUrl = '@Url.Action("GetData")'
$(primaryDropDown).cascade(secondaryDropdown, actionUrl);
});
Remember to add the $(document).ready
part, the page must be fully loaded before you try to make the drop downs cascade.
请记住添加$(document).ready
部分,在您尝试使下拉菜单级联之前,页面必须完全加载。
回答by Debendra Dash
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#country").change(function () {
$("#State").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("State")', // we are calling json method
dataType: 'json',
data: { id: $("#country").val() },
// here we are get value of selected country and passing same value
success: function (states) {
// states contains the JSON formatted list
// of states passed from the controller
$.each(states, function (i, state) {
$("#State").append('<option value="' + state.Value + '">' +
state.Text + '</option>');
// here we are adding option for States
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
<div>
@Html.DropDownList("country", ViewBag.country as List<SelectListItem>, "CountryName", new { style = "width: 200px;" })
</div>
<div>
</div>
<div>
@Html.DropDownList("State", ViewBag.country as List<SelectListItem>)
</div>
From controller I am getting the values
从控制器我得到值
public async Task<ActionResult> Country()
{
Country co = new Country();
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select", Value = "0" });
li.Add(new SelectListItem { Text = "India", Value = "1" });
li.Add(new SelectListItem { Text = "Nepal", Value = "2" });
li.Add(new SelectListItem { Text = "USA", Value = "3" });
li.Add(new SelectListItem { Text = "Kenya", Value = "4" }); ;
ViewBag.country= li;
return View();
}
public JsonResult state(string id)
{
List<SelectListItem> states = new List<SelectListItem>();
states.Add(new SelectListItem { Text = "--Select State--", Value = "0" });
switch (id)
{
case "1":
states.Add(new SelectListItem { Text = "MP", Value = "1" });
states.Add(new SelectListItem { Text = "UP", Value = "2" });
break;
case "3":
states.Add(new SelectListItem { Text = "USA1", Value = "3" });
states.Add(new SelectListItem { Text = "USA2", Value = "4" });
break;
}
return Json(new SelectList(states, "Value", "Text", JsonRequestBehavior.AllowGet));
}