I am trying to emptying a dropdownlist created by a Dropdownlistfor
@Html.DropDownListFor(model => model.Id2, (List<SelectListItem>)ViewBag.List2)
after changing the selected value of another dropdownlistfor
@Html.DropDownListFor(model => model.Id1, (List<SelectListItem>)ViewBag.List1)
This is my javascript code
function changeList(value, that) {
//value is equal to the selected value of List2
var self = $(that).find("#Id2");
$.ajax({
url: '@Url.Action("method", "controller")',
method: 'POST',
data: { 'value': value },
dataType: 'json',
success: function (data, textStatus, jqXHR) {
self.empty();
$.each(data, function (key, item) {
self.append($("<option></option>").val(item.Value).text(item.Text));
});
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
My problem is, when I change the selected value of List1, it manage to change the options of List2, but it doesn't display it.
It works when I don't click or have any interaction with List2 before changing selected value of List1.
It doesn't if I change the selected value of List 2 and then changing the selected value of List 1. (Well it works, but it won't display it correctly to the view).
EDIT
=>My javascript works<=, it won't just displaying it correctly to the view if I interact with it before changing my selected value of List 1 !
EDIT 2
My method in controller
[HttpPost]
public JsonResult method(long value)
{
try
{
var items= GetItems(value);
return Json(new List<SelectListItem>(items));
}
catch (Exception ex)
{
return Json(new { Result = Error, ex.Message });
}
}