我想知道是否有人可以帮助我。我在变量var_departmentID
中有一个值,数据库下拉列表包含可以传递给变量的相同值。我想将下拉列表默认为变量中的值。我试过以下,但它不起作用。没有错误,它只是没有填充下拉列表。
@{var var_dbDepartment = Database.Open("Intranet");
var var_listDepartment = "SELECT Department_ID, Data FROM tbl_Department";
List<SelectListItem> listDepartmentData = new List<SelectListItem>();
bool departmentIsSelected = false;
listDepartmentData.Add(new SelectListItem { Text = "Please Choose...", Value = "0", Selected = true });
foreach(var var_item in var_dbDepartment.Query(var_listDepartment)) {
if(var_departmentID == var_item.Department_ID.ToString()) {
bool isSelected = true;
}
else {
bool isSelected = false;
}
listDepartmentData.Add(new SelectListItem{Text = var_item.Data, Value = var_item.Department_ID.ToString(), Selected = false});}}
@Html.DropDownList("Department", listDepartmentData, new { @class = "field", @id="department", @onchange="myFunction()" })
任何人都可以看到问题所在吗?
答案 0 :(得分:0)
我会按如下方式重写您的代码:
@{
var var_dbDepartment = Database.Open("Intranet");
var var_listDepartment = "SELECT Department_ID, Data FROM tbl_Department";
var data = var_dbDepartment.Query(var_listDepartment);
var items = data.Select(i => new SelectListItem{
Value = i.Department_ID.ToString(),
Text = i.Data,
Selected = i.Department_ID.ToString() == var_departmentID ? true : false
});
}
@Html.DropDownList("Department", "Please Choose...", items)
要获得更深入的报道,请查看HTML Helpers For Forms In Razor Web Pages。