我要达到的效果是在前面的下拉列表中选择机构,在后面的下拉列表中出现对应的部门。在部门表Dept中包含OrgID,但不是外键。在mvc中一般不设有外键。
helper中代码:
/// <summary> /// 根据机构id读取部门 /// </summary> /// <param name="id"></param> /// <returns></returns> public IList<Dept> GetDeptByOrgID(int id) { using (UUMContext uc = new UUMContext()) { var dept = from a in uc.Depts select a; if (id >= 0) { dept = dept.Where(a => a.OrgID == id); } IList<Dept> d = dept.ToList<Dept>(); return d; } }
controller中代码:
public ActionResult GetDeptByOrg(string orgId) { int orgid = 0; try { orgid = Convert.ToInt32(orgId); } catch { return Json(""); } return Json(GetDeptByOrgId(orgid, 0), JsonRequestBehavior.AllowGet); } /// <summary> /// 根据机构id获取部门 /// </summary> /// <param name="orgId"></param> /// <param name="defVal"></param> /// <returns></returns> public SelectList GetDeptByOrgId(int orgId, int defVal) { IList<Dept> items = deptHelper.GetDeptByOrgID(orgId); SelectList lists = new SelectList(items, "DeptId", "DeptName", defVal); return lists; }
View中代码:
<script type="text/javascript"> $(function () { $("#OrgID").change(function () { GetDept($(this).val()); }); }); function GetDept(orgid) { $("#DeptID").empty(); //$("#DeptID").append("<option value='0' selected='selected'>无</option>"); var option = { url: "/Dept/GetDeptByOrg", type: 'Get', chche: false, dataType: 'json', data: { orgId: orgid }, success: function (data) { //成功事件 $.each(data, function (i, item) { $("<option></option>") .val(data[i].Value) .text(data[i].Text) .appendTo($("#DeptID")); }); }, error: function (XMLHttpRequest, textStatus, errorThrown) { //发送失败事件 alert(textStatus); } }; //进行异步传输 $.ajax(option); } </script>
若要查看id,可查看源文件中的id值,保证jquery中的id值与之相同。