I have a case where I'm building a sign up application, there are model items that are in checkbox form. Each checkbox has a co-responding child collection/list.
If a user checks a box, a jquery call runs to a controller action to query the list to get the child items and return the matching list via JSON to the co-responding listbox.
That all works fine! The issue is only the binding.
Here's the JSON action that returns the child objects:
[HttpGet]
public ActionResult PickupKids(int id)
{
AccountFormEntities db = new AccountFormEntities();
var childItems = (from c in db.account_type_children
where c.groupID.Equals(id)
select c
).OrderBy(c => c.title)
.ToList();
List<SelectListItem> SelectedAccountChildren = new List<SelectListItem>();
foreach (var item in childItems)
{
SelectListItem selectListItem = new SelectListItem();
selectListItem.Text = item.title;
selectListItem.Value = item.id.ToString();
selectListItem.Selected = item.selected;
SelectedAccountChildren.Add(selectListItem);
}
return Json(SelectedAccountChildren, JsonRequestBehavior.AllowGet);
}
which returns to this Jquery event to populate the listbox:
if ($(this).prop('checked'))
{
$('.' + checkId).css("color", "black");
$('.' + checkId).css("font-weight", "Bold");
$('.' + checkId).css("font-size", "large");
$(divId).show(1000);
var url = '@Url.Action("PickupKids")';
$.ajax({
url: url,
type: 'GET',
cache: false,
data: { id: checkId },
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (json) {
$('.' + ListID).empty();
$.each(json, function (index, optiondata) {
$('.' + ListID).append("<option value='" + optiondata.Value + "'>" + optiondata.Text + "</option>");
});
}
});
Then, the listbox (which does fill correctly with the proper children:
@if (Model.AccountTypes[i].Account_type_options == "BDMS")
{
@Html.ListBoxFor(x => x.AccountTypeChildren, Model.SelectedAccountChildren, new { @class = SelectGroupId, @style = "height:150px; width:500px" })
}
here are the ViewModel definitions of the two model objects in the listbox:
public List<SelectListItem> AccountTypeChildren
{
get;
set;
}
public List<SelectListItem> SelectedAccountTypeChildren
{
get;
set;
}
and what is returned is the ids that are selected, but it returns them each as an instance of the 'selectedAccountTypeChildren' (example: selectedAccountTypeChildren = 10, selectedAccountTypeChildren=13) where it should read 'selectedAccountTypeChldren[110] value=true' etc.
Does anyone know how to get the list to bind properly? Thank You for any information
What I have tried:
I've tried modifying the list types, and tring to iterate the lists but the list comes up null in the action, but in fiddler it does show:
Body value
AccountTypes[4].Account_type_options INB
SelectedAccountTypeChildren 111
SelectedAccountTypeChildren 112