Skip to content
Advertisement

How to set ASP-Items value for SelectList via javascript ajax call

I have a states dropdown on a form, and when a user selects a state, I want the cities dropdown to populate with just the cities pertaining to that state.

I have 2 Select Boxes in my form view:

JavaScript

Then I have Javascript that gets the cities via ajax when the state is selected:

JavaScript

My ajax call to the controller:

JavaScript

My controller that gets the SelectListItems of Cities pertaining to the selected state:

JavaScript

Right now it returns the object to the success part of my ajax call, but how do I set the option items for that dropdown view javascript. This is what the data looks like that I get via javascript… I was hoping to set the asp-items value… but I am not sure how to do that exactly with Javascript. These are the cities it returns for Alabama, for example: enter image description here

Advertisement

Answer

So returning a dictionary from the controller sends an object to the ajax call. I had to figure out how to loop through the object in JS:

JavaScript
Advertisement