I have the following question regarding the MVC and Jquery. I would like to be able to call with JQuery an action serverside and then returned result bind to a drop down list.
At this moment i do have something like that but instead of SelectList i just get back an anonymous type collection.
I have following JQuery:
<script type="text/javascript">
(function ($) {
$.fn.cascade = function (options) {
var defaults = {};
var opts = $.extend(defaults, options);
return this.each(function () {
$(this).change(function () {
var selectedValue = $(this).val();
var params = {};
params[opts.paramName] = selectedValue;
$.getJSON(opts.url, params, function (items) {
opts.childSelect.empty();
$.each(items, function (index, item) {
opts.childSelect.append(
$('<option/>')
.attr('value', item.Id)
.text(item.Name)
);
});
});
});
});
};
})(jQuery);
$(function () {
$('#Location_CountryId').cascade({
url: '@Url.Action("Regions")',
paramName: 'countryId',
childSelect: $('#Location_RegionId')
});
$('#Location_RegionId').cascade({
url: '@Url.Action("Cities")',
paramName: 'regionId',
childSelect: $('#Location_CityId')
});
});
</script>
Which calls this action in mvc 3:
public ActionResult Cities(int regionId)
{
IList cities;
using (DatingEntities context = new DatingEntities())
{
cities = (from c in context.cities
where c.RegionID == regionId
select new
{
Id = c.CityId,
Name = c.Name
}).ToList();
};
return Json(cities, JsonRequestBehavior.AllowGet);
}
My question, can i then return SelectList instead of IList and bind it properly?
Could you provide an example with my code please? I have more complex behavriou just for simpleness i posted only part of.
Thanks