I have a "Leads" table which has a one to many relationship to "Employees" table. I also have created a leadViewModel class because I need some additional info for the Lead (Like addresses and phones etc.)
Here is the Lead class:
public partial class Leads
{
[Key]
public int LeadID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[NotMapped]
public string FullName { get { return FirstName + " " + LastName; } }
public int EmployeeID { get; set; }
public virtual Employees Employees { get; set; }
}
Employee Class:
public partial class Employees
{
public Employees()
{
this.Leads = new HashSet<Leads>();
}
[Key]
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[NotMapped]
public string FullName { get { return FirstName + " " + LastName; } }
public virtual ICollection<Leads> Leads { get; set; }
}
leadViewModel:
public class LeadViewModel
{
public Leads _leads { get; set; }
public Addresses _addresses { get; set; }
public Phones _phones { get; set; }
public Emails _emails { get; set; }
public IEnumerable<SelectListItem> EmployeesSelectListItem { get; set; }
}
Now I want to have a dropdown list in the "Create" view. I am not sure what to do. Here is what I did and got errors.
LeadsController Create Get:
// GET: Leads/Create
public ActionResult Create()
{
ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FirstName");
return View();
}
LeadsController Create Post:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "_leads,_addresses,_phones,_emails,EmployeesSelectListItem")] LeadViewModel leadVM)
{
if (ModelState.IsValid)
{
using (TransactionScope leadScope = new TransactionScope())
{
db.Leads.Add(leadVM._leads);
db.SaveChanges();
leadScope.Complete();
return RedirectToAction("Index");
}
}
ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FirstName", leadVM._leads.EmployeeID);
return View(leadVM);
}
and finally the create view:
@model CL_AHR_CRM.ViewModels.LeadViewModel
...
<div class="form-group">
@Html.LabelFor(model => model._leads.EmployeeID, "EmployeeID", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(x => x._leads.EmployeeID, new SelectList(Model.EmployeesSelectListItem, "EmployeeID", "FirstName"), htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model._leads.EmployeeID, "", new { @class = "text-danger" })
</div>
</div>
I repeat my question: How can I use dropdownliast in a view when using a viewModel like this because obviously what I have done is not the way and is not working. I get the error: "Object reference not set to an instance of an object." on the Html.DropdownlistFor(...) in create view.