下拉框绑定

本文介绍了在MVC模式中如何使用LINQ查询从数据库获取数据,并将其绑定到下拉框。通过控制器的方法获取国家、民族和病人类别的数据,并在页面上使用JavaScript函数实现动态绑定。特别是民族的下拉框会根据选定的国家ID进行更新。
摘要由CSDN通过智能技术生成

开发工具与关键技术: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);

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值