【发布时间】:2018-08-05 09:41:33
【问题描述】:
以下代码是将 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 期间,div id='HiddenIntake' 内的 DropDownList 使用 jquery 隐藏。在文本框 id='UserID' 填充值之后,我将此值传递给控制器并更新 Intake DropDownList 并使用 jquery 显示如下:
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 是更新 Intake DropDownList 但问题是控制器没有返回 View,因此 ViewBag 不起作用。而如果是返回View,那么ajax就不会落入成功函数中。
有没有办法让 ViewBag 工作并进入 ajax 中的成功功能???
【问题讨论】:
-
ViewBag没有意义。您的return Json(result, JsonRequestBehavior.AllowGet);是正确的,然后在成功回调中您的循环通过集合并生成新选项(请参阅better way to load 2 dropdown in mvc 示例 -
然后完全停止使用
VIewBag,并使用视图模型并通过使用@DropDownListFor(m => m.YourProperty, Model.YourSelectList)绑定到您的视图模型来正确生成下拉列表 -
好的,谢谢你的建议,我很期待,顺便说一句,你有什么好的资源来了解如何使用视图模型吗?
标签: javascript jquery ajax asp.net-mvc html-helper