Geting SelectList to view MVC using AJAX / jQuery

I have a C # MVC application that populates a drop down list based on the selected date. Once the date is selected, I submit it to action via AJAX / jQuery. The action gets a list of items returned for this date.

That is where my problem is. I did this before when I make a partial view of an action and pass it a SelectList as a model. However, I just want to do this inline in the original view, so I hope that somehow I can return the SelectList and from there make some kind of magical Javascript / JQuery to put it in the drop-down list.

Has anyone ever done this before? If so, what am I on the client side after calling load () to return a SelectList?

I did something similar earlier when I just returned a string or other value that should display as plain text:

$("#returnTripRow").load("/Trip.aspx/GetTripsForGivenDate?date=" + escape(selection)); 

But I'm not sure how to intercept the data and convert it to amhtml.DropDown () or the equivalent.

Any ideas?

Thanks,

Chris

+6
javascript jquery ajax drop-down-menu asp.net-mvc
source share
1 answer

Suppose you have a controller action that will pass data for a dropdown menu:

 public ActionResult Cars() { return Json(new[] { new { id = "bmw", name = "BMW" }, new { id = "mer", name = "Mercedes" }, new { id = "aud", name = "Audi" } }, JsonRequestBehavior.AllowGet); } 

And in your opinion:

 $.getJSON('/home/cars', { }, function(cars) { var list = $('select#cars'); list.find('option').remove(); $(cars).each(function(index, car) { list.append('<option value="' + car.id + '">' + car.name + '</option>'); }); }); 
+17
source share

All Articles