我正在尝试使用数据库中的数据创建一个下拉列表。我没有结果。下面是代码。有什么想法吗?
谢谢!
控制器:
DepartmentsConn dCon = new DepartmentsConn();
public ViewResult Employees(string Dept)
{
ViewBag.Departments= new SelectList(dCon.Departments, "ID", "Dept");
var employees = from m in db.Employees
where m.Dept == Dept ||Dept == null ||Dept == ""
select m;
return View(employees.ToList());
}
查看:
@Html.DropDownList("Departments", ViewBag.Departments as SelectList)
答案 0 :(得分:0)
这是对第二部分有关单击ddl进行重定向的答案。
首先将一个占位符添加到选择列表,因此用户必须进行选择:
@Html.DropDownList("Departments", ViewBag.Departments as SelectList, "Select a department...")
然后添加在更改时触发的jQuery,获取Id值并将其发送到Controller:
$(function () {
$("#Departments").on("change", function () {
var deptId = $(this).val();
var routeVal = { Id: deptId };
var url = '@Url.Action("Department", "Home")';
$.ajax({
url: url,
type: 'POST',
data: routeVal
}).done(function (result) {
window.location.href = result.newUrl;
})
})
})
这是一次双跳,所以我相信它可以得到改善。基本上,它获取Id值,然后将其发送到名为“ SetUrl”的控制器操作,该操作将新的URL返回给ajax函数,然后将用户定向到.done()函数中的新url。在这种情况下,新的URL是Home / Department / 1,它返回到控制器以返回新视图:
public ActionResult Department(int Id)
{
// Get the department data for this ID
// Fill a model then return it
return View(model);
}