根据从另一个DropDownList中选择的值填充一个DropDownList [英] Fill a DropDownList based on the selected value from another DropDownList
问题描述
我试图基于MVC .NET Core 2.2中另一个DropDownList的值来填充DropDownList.
I was trying to fill a DropDownList based on the value from another DropDownList in MVC .NET Core 2.2.
<div class="form-group row">
<label class="col-sm-2 col-form-label">Type :</label>
<div class="col-sm-10">
<select asp-for="SelectedType" asp-items="@(new SelectList(Model.TypeList, "TypeName", "TypeDescription"))" class="custom-select custom-select-sm">
</select>
</div>
</div>
public class Type
{
public string TypeName { get; set; }
public string TypeDescription { get; set; }
}
我不熟悉JavaScript或Ajax,也无法在Google上弄清楚示例.
I'm not familiar with JavaScript or Ajax and I can't figure the example on Google out.
因此,基本上,如果在DropDownList中选择类型"(例如"A"),则必须使用基于"A"的字符串列表来填充DropDownList,而当您选择"B"时,则需要使用a来填充DropDownList.基于"B"的字符串列表.
So basically if you select in DropDownList "Type" for example "A", the DropDownList needs to be filled with a list of strings based on "A", when you select "B" the DropDownList needs to be filled with a list of strings based on "B".
有人可以给我一个很简单的例子吗?
Can someone provide me a very easy example?
像这样吗?
$(document).ready(function()
{
$("#ddlEmployee").on("change", function()
{
$.ajax(
{
url: '/Home/GetTypesBasedOnValueFromOtherDropDownList' + $(this).attr("value"),
type: 'GET',
data: "",
contentType: 'application/json; charset=utf-8',
success: function(data)
{
$("#???").html(data);
},
error: function()
{
alert("error");
}
});
});
});
< /script>
推荐答案
您可以将第一个 select
的选定值传递给服务器端,查询数据库并将结果成功返回给客户端.Ajax的回调函数以填充第二个 select
.以下代码供您参考:
You can pass selected value of the first select
to server side , query the database and return result back to client side , in success callback function of ajax to fill the second select
. Code below is for your reference :
$("#SelectedType").on("change", function () {
$.ajax({
type: 'GET',
url: "/home/GetTypesBasedOnValueFromOtherDropDownList",
contentType: 'application/json',
data: { Type: $("#SelectedType").val() },
success: function (data) {
var s = '<option value="-1">Please Select a Course</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].courseCode + '">' + data[i].courseName + '</option>';
}
$("#secondSelect").html(s);
}
});
})
服务器端:
public IActionResult GetTypesBasedOnValueFromOtherDropDownList(string Type)
{
//you can query database instead
List<AdmInstCourses> admInstCourses = new List<AdmInstCourses>();
admInstCourses.Add(new AdmInstCourses() { CourseCode = 1, CourseName = "name1", Units = "3.2" });
admInstCourses.Add(new AdmInstCourses() { CourseCode = 2, CourseName = "name2", Units = "3.3" });
return new JsonResult(admInstCourses);
}
这篇关于根据从另一个DropDownList中选择的值填充一个DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!