I’m working on an mvc .net web application and I’m using Entity Framework. In my model, I have an entity called “utisateur” (user) and every user has one or more users that supervise him. What I want to do is generate a multi select list box that contains the list of all users inorder to select the new users’ supervisors.
I tried to to that but after filling my form for creating a new user and submitting it i got this error : Object reference not set to an instance of an object, however I got the select list and I selected items from it. (the empty object is “model.selectedusers” but I don’t know why is it empty!)
Here is my model class :
public class util
{
public util()
{
user = new utilisateur();
listesups = Getutilisateurs(null);
}
public utilisateur user { get; set; }
public int[] selectedusers;
public string nom_role { get; set; }
public MultiSelectList listesups { get; set; }
public MultiSelectList Getutilisateurs(int[] selectedValues)
{
var db = new BDGestionEntities();
List<utilisateur> utilisateurs = db.utilisateurs.ToList();
return new MultiSelectList(utilisateurs, "id", "login", selectedValues);
}
}
Here is my controller :
public ActionResult Create2()
{
util u = new util();
u.listesups = new MultiSelectList (db.utilisateurs, "id", "login");
return View(u);
}
[HttpPost]
public ActionResult Create2(util model)
{
utilisateur u = new utilisateur();
try
{
foreach (var selecteduse in model.selectedusers)
{
utilisateur utilisateur = db.utilisateurs.Where(c => c.id == selecteduse).FirstOrDefault();
u.superieur.Add(utilisateur);
}
}
catch(Exception ex)
{
Logger.Error(ex.Message, "Erreur ajout supérieurs");
}
u.nom = model.user.nom;
u.prenom = model.user.prenom;
u.solde_conge = model.user.solde_conge;
u.email = model.user.email;
u.login = model.user.login;
u.pwd = model.user.pwd;
role role = new role();
role = db.roles.Where(c => c.nom_role == model.nom_role).FirstOrDefault();
u.role = role;
db.utilisateurs.AddObject(u);
db.SaveChanges();
ViewBag.id_role = new SelectList(db.roles, "id", "nom_role", model.user.id_role);
return RedirectToAction("index");
}
Here is the part of the view that contains the selectlist
@Html.ListBoxFor(model => model.selectedusers, Model.listesups)
And here what I got before submitting the form, as you can see here the view contains the seleclist but selected items are not saved

There is no built in support for including multiple items (or an arry or items) into the viewModel from View by default in MVC 3. That is why you are losing the selected value.
There are many ways of making it happen but the easier one is to modify your method’s signature to include form collection and query the values of the listbox.
Your
Create2method should look like: