In my view I have one dropdown Role and second ListBox as Permissions. I want to change the values in ListBox as User selects the values in Dropdown Role
<tr>
<td>@Html.Label("","Role")</td>
<td>@Html.DropDownListFor(x => x.Role, @ViewBag.role as SelectList, new { @class = "dropdown"} )</td>
</tr>
<tr>
<td>@Html.Label("","Permissions in Role")</td>
<td>@Html.ListBox("permissions", @ViewBag.permissions as SelectList, new { @class = "chosen-select", data_placeholder = "Add Permissions to Role...", style = "width:500px;", tabindex = "4"})</td>
</tr>
In My js file (Updated After Stephen Suggestion)
$(document).on('change', '#Role_RefID', function () {
var selection = $(this).val();
$.getJSON(window.location.pathname + "/getPermissions?id="+selection, function (result) {
var ddl = $('#permissions');
ddl.empty().trigger("chosen:updated");
$(result).each(function () {
$(document.createElement('option'))
.attr('value', this.Id)
.text(this.Value)
.appendTo(ddl)
.attr('selected',"selected")
;
});
ddl.trigger("chosen:updated");
});
});
getPermissions (Updated after Stephen Suggestion)
public JsonResult getPermissions(int id)
{
List<Reference> perms = rep.permsInRole(id);
var res = perms.Select(p => new { Id = p.RefID, Value = p.Description }).Distinct().ToList();
return Json(res, JsonRequestBehavior.AllowGet);
}
ListBox displays the initial values from DB but when I change the values in dropdown It doesnt clear the contents of Listbox and also doesnt display the new values in ListBoxListBox