从数据库填充下拉列表(依赖项下拉列表)时出现问题



我想用另一个下拉列表填充下拉列表。 这是类别和子类别。

第一个下拉列表是主要类别 数据库中的字段: 1.Id 2.猫名

第二个下拉列表是子类别 数据库中的字段: 1.Id 2.主界面 3.猫名

嗯,这是真的, 现在: 我的剃须刀代码:

@functions {
public List<MainProduceCategory>
CatList(int mainCatId)
{
ApplicationDbContext _context = new ApplicationDbContext();
IMainProduceRepository cats = new MainProduceRepository(_context);
return cats.GetCats(items);
}
}

代码为 true,并按 maincatId 返回子类别。

<div class="form-group">
<label class="control-label"></label>
<select class="custom-select simplebox form-control" onChange="myjs(this.value);">
<option value="1">movies</option>
<option value="2">softwares</option>
</select>
</div>

代码是剃刀中的主要类别。

<div class="form-group">
<label class="control-label"></label>
<select id="subcats" class="custom-select simplebox form-control">
<option value="0">not select</option>
</select>
</div>

代码是剃刀中的子类别。

现在: 如何按主下拉列表填写第二个下拉列表?

jquery代码:但不起作用。

<script language="javascript">
function myjs(state) {
with (document.getElementById('subcats')) {
options.length = 0;
if (state == 0) {
options[0] = new Option('mainSelect', '0');
}
if (state == "1") {
for (var i = 0; i <= @CatList(1).Count; i++) {
options[i] = new Option(@CatList(1).Select(c=>c.CatName)[i]);
}
}
}
}
</script>

这是关于国家和城市之间的级联下拉列表的简单演示。您可以参考并根据需要进行修改

1.型号

public class Country
{
public int Id { get; set; }
public string CountryName { get; set; }
public List<City> Cities { get; set; }
}
public class City
{
public int Id { get; set; }
public string CityName { get; set; }
public Country Country { get; set; }
}

2.使用jQuery AJAX绑定城市列表下拉列表

<div>
<select asp-items="@ViewBag.Country" id="countrylist">
<option>Select</option>
</select>
</div>
<div>
<select id="citylist"></select>
</div>
@section Scripts
{
<script type="text/javascript">
//Insert default item "Select" in dropdownlist on load
$(document).ready(function () {
var items = "<option value='0'>Select</option>";
$("#citylist").html(items);
});
//Bind City dropdownlist
$("#countrylist").change(function () {
var countryId = $("#countrylist").val();
var url = "/Countries/GetCityList";
$.getJSON(url, { CountryId: countryId }, function (data) {  
var item = "";
$("#citylist").empty();
$.each(data, function (i, city) {
item += '<option value="' + city.value + '">' + city.text + '</option>'
});
$("#citylist").html(item);
});
});
</script>
}

3.在国家控制器中添加获取城市列表方法

public async Task<IActionResult> CountryList()
{
ViewBag.Country = new SelectList(_context.Country, "Id", "CountryName");
return View();
}
[HttpGet]
public JsonResult GetCityList(int CountryId)
{
var citylist= new SelectList(_context.City.Where(c => c.Country.Id == CountryId),"Id","CityName");
return Json(citylist);
}

最新更新