I am trying to return the value of a ViewBag into a html dropdown (on a form) in my View in the <script> area using jQuery. I trigger the Controller side based on the value of another dropdown (on a form) as follows:
View (triggers the GetBrandsForDropdown action method):
$.ajax({
` url: '/Home/GetBrandsForDropdown', });
Controller:
public IActionResult GetBrandsForDropdown()
{
var brandListing = context.Brands.OrderBy(b => b.BrandName).ToList();
ViewBag.brandList = brandListing;
return View();
}
I've debugged this and the ViewBag has values.
View:
var myBrands = '@(ViewBag.brandList)';
alert("The value is: " + myBrands);
I've tried a number of iterations to retrieve the value in the ViewBag. The one above is the only one that allowed processing to continue (i.e. the alert (which included my text) displayed on my screen). However, the value of the ViewBag is blank. Help regarding how to retrieve the value(s) to the View and add them to my <form> dropdown would be very much appreciated.
ajax's success, perform the actions you want?