Multi select list box asp mvc-Collection of common programming errors
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 i got this error : Object reference not set to an instance of an object.
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 MultiSelectList listesups { get; set; }
public MultiSelectList Getutilisateurs(int[] selectedValues)
{
var db = new BDGestionEntities();
List utilisateurs = db.utilisateurs.ToList();
return new MultiSelectList(utilisateurs, "id", "login", selectedValues);
}
}
And here is the part of the view that contains the list box :
@Html.ListBoxFor(model => model.selectedusers, Model.listesups)
Here is the controller
public ActionResult Create2()
{
return View();
}
[HttpPost]
public ActionResult Create2(util model)
{
utilisateur u = new utilisateur();
if (model.selectedusers != null)
{
foreach (var selecteduse in model.selectedusers)
{
int selecteduseId = selecteduse;
utilisateur utilisateur = db.utilisateurs.Where(c => c.id == selecteduseId).FirstOrDefault();
u.superieur.Add(utilisateur);
}
}
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.nom_role = model.nom_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");
}
And here is the error message
Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 44:
Role :
Line 45:
Line 47: Line 48: