Following code, is to populate IntakeName to a Html Helper DropDownlist
Controller Code :
public ActionResult Index()
{
ViewBag.intake = new SelectList(db.Intakes, "IntakeID", "IntakeName");
return View();
}
View Code :
@Html.DropDownList("intake", null, htmlAttributes: new { @class = "form-control" })
By default / During PageLoad the DropDownList inside a div id='HiddenIntake' is hide using jquery. After a textbox id='UserID' is fill with value then I pass this value to controller and update the Intake DropDownList and show back using jquery as below :
Jquery Ajax Code :
$(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();
}
});
Controller Code :
[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);
}
As you can see the ViewBag is to update the Intake DropDownList but the problem is the controller is not returning View so that ViewBag doesnt work. And if is returning View, then ajax won't fall into success function.
Is there anyway to make the ViewBag work and fall into success function in ajax ???