I have a C# MVC application which is populating a dropdown based on a date selected. Once the date is selected I am sending it to an action via AJAX/jQuery. The action gets a list of items to return for that date.
Here is where my problem is. I have done it previously where I render a partial view from the action and pass it the SelectList as the model. However, I really just want to do it inline in the original view, so I'm hoping there is some way I can return the SelectList and from there do some magic Javascript/JQuery to put it into a dropdown.
Has anybody ever done this before? If so, what do I on the client end after calling the load() to return the SelectList?
I've done something like this previously, when I was just returning a string or other value to be rendered as straight text:
$("#returnTripRow").load("/Trip.aspx/GetTripsForGivenDate?date=" + escape(selection));
But I'm not sure how to intercept the data and morph it into am Html.DropDown() call, or equivalent.
Any ideas?
Thanks,
Chris
Supposing you have a controller action that will feed the data for the dropdown:
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 view:
$.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>');
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With