for last two days i was trying to figure out how to update a checkboxlist dynamicly when a new item in dropdownlist is selected by help of javascript.
Ive done same thing for a week ago where i should do update to a from a dropdownlist to a dropdownlist.
What ive got so far :
View
@using (Html.BeginForm())
{
@Html.DropDownListFor(x => x.User, (IEnumerable<SelectListItem>)Model.UserList, "-- vælg bruger --")
if (Model.checkboxlist != null)
{
for (var i = 0; i < Model.checkboxlist.Count; i++)
{
<div class="editor-label">
@Html.CheckBoxFor(c => Model.checkboxlist[i].check)
@Html.LabelFor(c => Model.checkboxlist[i].Id, Model.checkboxlist[i].Id)
@Html.HiddenFor(c => Model.checkboxlist[i].Id)
</div>
}
}
}
<script type="text/javascript">
$('#User').change(function () {
alert('HEJ!');
var selectedUser = $(this).val();
alert(selectedUser);
if (selectedUser != null && selectedUser != '-- vælg bruger --' && selectedUser != '') {
$.getJSON('@Url.Action("getPdfCheckBoxList","Admin")', { username: selectedUser },
function (employee) {
var checkboxlist = $('#checkboxlist');
checkboxlist.empty();
$.each(employee, function (index, employee) {
checkboxlist.append($('<checkbox/>', {
checked = 'false'
}));
});
});
}
});
</script>
when i am loading view Model.checkboxlist is null cause i dont return anything to model apart of dropdownlist items.
ControllerAction :
public ActionResult getPdfCheckBoxList(String username)
{
MethodService service = new MethodService();
var list = new List<PDFCheckBoxList>();
foreach (var pdfCheckBoxList in getPDFFileNames(username))
{
list.Add(new PDFCheckBoxList { check = false, Id = pdfCheckBoxList });
}
return Json(list, JsonRequestBehavior.AllowGet);
}
Right now even Alert(“HEJ”) doesnt even get fired, and i simply cant figure out why… Help please?
You could use partial views and have your controller action return a partial and build the markup on the server instead of doing it on the client:
and then define
_checkboxlist.cshtml:and finally the editor template
~/Views/Shared/EditorTemplates/PDFCheckBoxList.cshtmlwhich will be rendered for each element:Now you could modify your javascript like so:
and finally your
getPdfCheckBoxListaction:If you want to build the markup on the client and have the controller action return JSON I would recommend you using some javascript templating framework.