在我的控制器中,我在我的视图中显示了这个类别列表。这是我申请的报告部分。
public SelectList getFields()
{
List<SelectListItem> field = new List<SelectListItem>();
field.Add(new SelectListItem { Text = "Department", Value = "dept" });
field.Add(new SelectListItem { Text = "Referrer", Value = "ref" });
field.Add(new SelectListItem { Text = "Monthly", Value = "cd_key" });
return new SelectList(field, "Value", "Text");
}
public ActionResult HR_RecRep()
{
ViewBag.fields = getFields();
return View();
}
然后在我的视图中:
<script type="text/javascript">
$(document).ready(function () {
//this function will call the views with id=category
$('#fields').change(function () {
//Get the selected value from the dropdownlist
var rep = $(this).val();
//alert(cat);
if (rep.toUpperCase() == "DEPT") {
var text = document.getElementById("dept");
text.style.display = "inline";
$.getJSON('/Reports/getDepartment/', function (data) {
var items = '<option>Select Department...</option>';
$.each(data, function (i, department) {
items += "<option value='" + department.Value + "'>" + department.Text + "</option>";
});
$('#department').html(items);
});
var textValue = document.getElementById("ref");
textValue.style.display = "none";
}
});
});
</script>
<div style="border:0px solid black;width:950px;">
Reports By: @Html.DropDownList("fields", String.Empty)
<span id="dept" style="display:none;"><select id="department" name="department"></select></span>
<span id="ref" style="display:none;"><select id="referrer" name="referrer"></select></span>
在我看来,它成功显示了Reports By Section的字段。 每当我选择&#34; dept&#34;在下拉列表中,它引用了类别中的部门,它应该显示数据库中所有部门的下拉列表。
这是我的控制器,用于获取部门列表。
public SelectList getDepartment()
{
ViewBag.department = new SelectList(db.rms_departments, "dept_id", "dept_shortname");
return ViewBag;
}
当我尝试使用代码时,当我在报告中选择部门时,它不会显示部门的下拉列表。而且,对于Referrer,当我从下拉列表中选择它时,它应该显示数据库中所有员工的下拉列表。
你能帮助我吗? 非常感谢。也许我的脚本有什么关系?
答案 0 :(得分:1)
您的问题是您没有从您的操作方法返回JSON,修改您的操作以返回JSON:
public ActionResult getDepartment()
{
var departments = db.rms_departments.Select(x=>
new
{
dept_id=dept_id,
dept_shortname=dept_shortname
});
return JSON(departments,JsonRequestBehavior.AllowGet);
}
并在脚本中修改行:
items += "<option value='" + department.Value + "'>" + department.Text + "</option>";
为:
items += "<option value='" + department.dept_id+ "'>" + department.dept_shortname+ "</option>";
答案 1 :(得分:-1)
我已经得到了答案。我只是将我的控制器代码更改为:
public JsonResult getDepartment()
{
return Json(new SelectList(db.rms_departments, "dept_id", "dept_shortname"), JsonRequestBehavior.AllowGet);
}