I'd like to refresh an MVC Dropdownlist from a JsonResult method.
Here's the public method that returns the result:
[HttpPost]
[ValidateAntiForgeryToken]
[CustomAuthorize]
public JsonResult GetHtmlApplicationSelectionList()
{
try
{
List<SelectListItem> applicationList = new List<SelectListItem>();
SelectListItem defaultApplicationValue = new SelectListItem();
defaultApplicationValue.Value = "0";
defaultApplicationValue.Text = "-- Select Application --";
defaultApplicationValue.Selected = true;
applicationList.Add(defaultApplicationValue);
foreach (var app in businessLogic.GetApplications().Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.Name }))
{
applicationList.Add(app);
}
return Json(new { result = "success", list = applicationList }, JsonRequestBehavior.AllowGet);
}
catch(Exception ex)
{
return Json(new { result = "failure", message=ex.Message}, JsonRequestBehavior.AllowGet);
}
}
And here's the jQuery function that calls the POST method to get the updated list of applications:
function UpdateApplicationList() {
$.ajax({
url: 'Global/GetHtmlApplicationSelectionList',
type: 'POST',
dataType: 'json',
success: function (data) {
$('.applicationSelector').html('');
$('.applicationSelector').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
}
How can I force the $(.applicationSelector') dropdownlist to contain the new list without having to loop through the list retured as JSON? Is it possible to return the html of the list( applicationList) and just refresh the html using $('.applicationSelector').html(data); ?
You need to append an <option> for each item.
This is the answer taken from this post which provides a pretty simple and straight forward example.
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($('<option>', { value : key })
.text(value));
});
Where var selectValues is your JSON list
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