Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh MVC Dropdownlist

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); ?

like image 440
codeg Avatar asked Feb 24 '26 08:02

codeg


1 Answers

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

like image 86
Ju66ernaut Avatar answered Feb 26 '26 21:02

Ju66ernaut