我正在尝试将 JSON 数据绑定(bind)到下拉列表
我的场景是我想获取数据并绑定(bind)到动态下拉列表,
在单独的类中,我使用 linq 来获取数据,例如
public SelectList getProjects()
{
IEnumerable<SelectListItem> projectslist = (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
return new SelectList(projectslist, "Value", "Text", PROJ_ID);
}
在 Controller 中:
ViewBag.ProjectList=(from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
在 View 中:
@for (int i = 0; i <2; i++)
{ {
@Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { @class = "ddlProjectvalue" })
}
现在,我正在尝试如果我们有三个下拉列表,我们在第一个下拉列表中选择一个列表项不应显示在第二个下拉列表中,并且在第三个下拉列表中不应显示我之前选择的两个列表项编写脚本如下:
<script>
$(document).ready(function () {
$('.ddlProjectvalue').change(function () {
debugger;
var selectedValue = $(this).val();
if (selectedValue != null && selectedValue != '') {
debugger;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/Employer/GetDDLData?selectedValue="+selectedValue,
data: "{}",
dataType: "Json",
success: function (data) {
// first remove the current options if any
$('.ddlProjectvalue').find('option').remove();
// next iterate thru your object adding each option to the drop down\
$(data).each(function (index, item) { // GETTING ERROR HERE
debugger;
$('.ddlProjectvalue').append($('<option></option>').val(item.Value).html(item.Text));
});
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
}
});
});
</script>
我从 Controller 返回 JSON 数据:
public ActionResult GetDDLData(string selectedValue)
{
int projectid = Convert.ToInt32(selectedValue);
IEnumerable<SelectListItem> projectslist = (from proj in db.PROJECTs where proj.IS_DELETED == "N" && proj.ID != projectid select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
var result = new SelectList(projectslist, "Value", "Text", tm.PROJ_ID);
return Json(result, JsonRequestBehavior.AllowGet);
}
我已经尝试过了,但是出现了错误
"Syntax error, Unrecognized Expression"
我哪里做错了,请任何人帮助我。
最佳答案
这将帮助你:
$.ajax({
url: "@Url.Action("GetDDLData","Employer")",
data: {selectedValue:selectedValue},
dataType: "json",
type: "GET",
error: function () {
alert(" An error occurred.");
},
success: function (data) {
var optionhtml1 = '<option value="' +
0 + '">' + "--Select State--" + '</option>';
$(".ddlProjectvalue").append(optionhtml1);
$.each(data, function (i) {
var optionhtml = '<option value="' +
data[i].Value + '">' +data[i].Text + '</option>';
$(".ddlProjectvalue").append(optionhtml);
});
}
});
关于c# - 如何使用 jQuery 将 JSON 数据绑定(bind)到 Asp.net MVC 中的下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22928756/