I am trying to save an object that contains a value coming from a dropdownbox (SelectList). I am getting a Nullpoint for some reason when trying to save. The Nullpointer is thrown in the piece of code that you see in my view below:
<div class="form-group">
@Html.LabelFor(model => model.RoleName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Roles, new SelectList(Model.Roles, "Value", "Value"), new { @class = "text-danger AddMemberControls" })
</div>
</div>
I chose a value from the dropdown on the screen, then click save, but it seems the model doesn't pass on the value. My model (ViewModel) looks like this:
public class AdminViewModel
{
public int MemberID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MemberEmail { get; set; }
public string Password { get; set; }
public IEnumerable<SelectListItem> Roles { get; set; }
public string RoleName { get; set; }
}
The controller looks like this
[HttpPost]
public ActionResult AddAdmin(AdminViewModel model)
{
//var selectedVal = new SelectList(model.Roles);
if(ModelState.IsValid)
{
var admin = new Admin()
{
FirstName = model.FirstName,
LastName = model.LastName,
MemberEmail = model.MemberEmail
// RoleName = selectedVal.DataTextField
...
};
}
...
return View("AddAdmin");
}
When running in debug mode, the ModelState.IsValid
evaluates to false, and then the view throws the exception mentioned above.
In case you want to see how I populate the Dropdownlist in my HttpHet
, here is the code
[HttpGet]
public ActionResult AddAdmin()
{
DataAccessLayer.ColoContext col = new DataAccessLayer.ColoContext();
List<Roles> list = new List<Roles>(col.Roles.ToList());
AdminViewModel viewMod = new AdminViewModel();
//viewMod.Roles = new SelectList(list);
viewMod.Roles = col.Roles.ToList().Select(x => new SelectListItem()
{
Value = x.RoleName,
Text = x.RoleDescription
}).ToList();
return View(viewMod);
}