下面的代码是将IntakeName填充到Html Helper DropDownlist
控制器代码:
public ActionResult Index()
{
ViewBag.intake = new SelectList(db.Intakes, "IntakeID", "IntakeName");
return View();
}
查看代码:
@Html.DropDownList("intake", null, htmlAttributes: new { @class = "form-control" })
默认情况下,/在PageLoad期间,使用jquery隐藏div id='HiddenIntake‘中的DropDownList。在文本框id='UserID‘填充了值之后,我将这个值传递给控制器,并使用jquery更新入口DropDownList并显示出来,如下所示:
Jquery Ajax代码:
$(document).ready(function(){
var x = $('#UserID').val();
if (x.length > 0) {
$.ajax({
type: "POST",
url: "/Payment/IntakeDropDownList",
data: { 'values': x },
success: function () {
$('#HiddenIntake').show();
},
error: function () {
alert('Failed');
}
});
} else {
$('#HiddenIntake').hide();
}
});
控制器代码:
[HttpPost]
public ActionResult IntakeDropDownList(int values)
{
var result = (from t in db.EnrollmentDetails
join i in db.Intakes on t.IntakeID equals i.IntakeID
where t.UserID == values
select new { i.IntakeID, i.IntakeName }).ToList();
ViewBag.intake = new SelectList(result, "IntakeID", "IntakeName");
return Json(result, JsonRequestBehavior.AllowGet);
}
正如您所看到的,ViewBag是要更新入口视图,但问题是控制器没有返回视图,因此ViewBag无法工作。如果返回的是View,那么ajax就不会进入成功函数。
有没有办法让ViewBag在ajax中成功运行?
发布于 2018-08-06 06:53:10
您只能使用ajax和Javascript来填充您的下拉列表,如下所示。
1.控制器端
public ActionResult Index()
{
// remove this line
// ViewBag.intake = new SelectList(db.Intakes, "IntakeID", "IntakeName");
return View();
}
2.视图侧: AJAX
var x = $('#UserID').val();
if (x.length > 0) {
$.ajax({
type: "POST",
url: "/Payment/PopulateIntakeDropDown",
data: { 'values': x },
success: function (data) {
// test some stuff here to see if there is no errors
// and at least an element in data
// then build your dropdown using javascript as following
// and i assume that you have an <select> element generated
// by your @Html.DropdownList helper with Id : intake
// so after all that, you can loop inside data (returned from controller)
// and for each element inside we will create an <option value=""></option>
// and do not forget to clear all "option" tags before populating
$('#intake option').remove()
$.each(data, function(index,elementIntake){
$('#intake').append('<option value="' + elementIntake.IntakeID + '">' + elementIntake.IntakeName + '</option>')
})
},
error: function () {
alert('Failed');
}
});
} else {
// depends of your personal choice of UI behavior, keep or remove
// $('#HiddenIntake').hide();
}
});
3.控制器POST方法
[HttpPost]
public ActionResult PopulateIntakeDropDown(int values)
{
var result = (from t in db.EnrollmentDetails
join i in db.Intakes on t.IntakeID equals i.IntakeID
where t.UserID == values
select new { i.IntakeID, i.IntakeName }).ToList();
// remove this line
// ViewBag.intake = new SelectList(result, "IntakeID", "IntakeName");
return Json(result, JsonRequestBehavior.AllowGet);
}
https://stackoverflow.com/questions/51693170
复制相似问题