我正在尝试创建一个带有数据库数据的Droplist。我没有得到任何结果。以下是代码。有任何想法吗?
谢谢!
控制器:
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)
这是对DDL单击重定向的第二部分的答案。
首先将一个占位符添加到选择列表中,因此用户必须进行选择:
@Html.DropDownList("Departments", ViewBag.Departments as SelectList, "Select a department...")
然后添加触发变化,获取ID值并将其发送给控制器的jQuery:
$(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。在这种情况下
public ActionResult Department(int Id)
{
// Get the department data for this ID
// Fill a model then return it
return View(model);
}