开发工具与关键技术:VS
作者:胡宁淇
撰写时间:2019年6月23日
MVC模式中我们给下拉框绑定数据可以通过在控制器中写方法查询数据库中的数据,然后绑定给下拉框,方法如下
我们首先在控制器中写出linq查询,查出下拉框中的数据
//国家查询
public ActionResult SelectCountry() {
List listCountry = (from tbCountry in myModel.D_Country
select new Select {
id=tbCountry.CountryID,
text=tbCountry.Country
}).ToList();
return Json(listCountry,JsonRequestBehavior.AllowGet);
}
//民族查询
public ActionResult SelectEthnic(int CountryId) {
List listEthnic = (from tbEthnic in myModel.D_Ethnic
where
tbEthnic.CountryID==CountryId
select new Select {
id=tbEthnic.EthnicID,
text=tbEthnic.EthnicName
}).ToList();
return Json(listEthnic,JsonRequestBehavior.AllowGet);
}
//病人类别
public ActionResult SelectPatientType() {
List listPatientType = (from tbPatientType in myModel.B_PatientType
select new Select {
id=tbPatientType.PatientTypeID,
text=tbPatientType.PatientType
}).ToList();
return Json(listPatientType,JsonRequestBehavior.AllowGet);
}
然后我们在页面写方法,首先我们写好下拉框绑定的方法,我们可以看到这个方法中有三个参数,它们分别是要绑定数据下拉框的ID,查询链接,还有值,这里我们只用到了两个参数,就是前面两个
function
createSelect(selectId, url, value) {
$.post(url, function (jsonData) {
if (selectId.indexOf(’#’) != 0) {
selectId = ‘#’ + selectId;
}
$(selectId).empty();//清空该元素
//内部前置内容
$(selectId).prepend(’<option
value="’ + 0
- ‘">’ + “–请选择–” + ‘’);
//创建option
for (k in jsonData) {
$(selectId).append(’’ + jsonData[k].text
- ‘’);
}
//设置选中值
if (value != undefined && value != null && value !=
‘’) {
$(selectId).val(value);
}
});
写完方法后我们就进行调用,值得注意的是民族的下拉框是根据国家的下拉框的值进行绑定
function loadSearchSelect()
{
//国家下拉框
createSelect(“searchCountryID”, “/RegistrationManagement/PatientManagement/SelectCountry”);
//证件类型下拉框
createSelect(“searchPapersTypeID”, “/RegistrationManagement/PatientManagement/SelectPapersType”);
//病人类别下拉框
createSelect(“searchPatientTypeID”, “/RegistrationManagement/PatientManagement/SelectPatientType”);
//民族下拉框
$("#searchCountryID").change(function () {
//获取选中的国家ID
var countryId = $("#searchCountryID").val();
createSelect(“searchEthnicID”, “/RegistrationManagement/PatientManagement/SelectEthnic?CountryId=” + countryId);
});
}
}