After some debugging, I found that Html.ListBoxFor()
method sends a collection of values (value
attribute from option
tag), and not the ListItem
objects (which I was expecting).
I created a transient property in the Model object of type int[]
, which receives that list of values, then create and insert the deattached objects into the list of LdapObjects. As follows:
Role.cs > Model
public class Role {
public virtual IList<LdapObjects> LdapGroups {
get;
set;
}
// Transient
public virtual int[] LdapGroupsSelected {
get;
set;
}
}
Create.aspx > View (right list in image above)
<%= Html.ListBoxFor(model => model.GruposLdapSelecionados,
new Iesi.Collections.Generic.HashedSet<CaduMVC.Models
.LdapObject>()
.Select(o => new SelectListItem() {
Value = o.Id.ToString(),
Text = o.Descricao,
}),
new { id="lbGruposSelecionados",
@class = "form-control",
style = "height: 120px;" }) %>
RoleController.cs > Controller
public ActionResult Create(Role obj) {
. . .
for(int i = 0; i < obj.LdapGroupsSelected.Length; i++) {
obj.LdapGroups.Add(new LdapObject(Convert.ToInt32(
obj.LdapGroupsSelected[i])));
}
session.Merge(obj);
}