I am having problem understanding as to why my model is not updating when I select a new value from my dropdownlist control?
Here is my model
public class UserViewModel
{
public Users users { get; set; }
public IEnumerable<SelectListItem> UserRoles { get; set; }
}
Controller
//GET
public ActionResult Edit(int id)
{
var vm = new UserViewModel();
vm.users = repository.GetById(id);
vm.UserRoles = db.UserRoles.Select(
x => new SelectListItem
{
Selected = true,
Text = x.UserRoleName,
Value = x.UserRoleID.ToString()
}
);
if (vm == null)
{
return HttpNotFound();
}
return View(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(UserViewModel model)
{
if(ModelState.IsValid)
{
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
And finally my View
<div class="form-group">
<label class="control-label col-md-2">User Role</label>
<div class="col-md-10">
@Html.HiddenFor(model => model.users.UserRoleID)
@Html.DropDownListFor(model => model.UserRoles, (IList<SelectListItem>)ViewBag.UserRoles, "-- Select One --", new { @class = "form-control" })
</div>
</div>
I have stepped through the code and in the Collection can see UserRoles
in the collection but I am not sure if I am passing the value correctly?
UPDATE
I have updated my POST
method for updating the model
public ActionResult Edit(int id, UserViewModel model)
{
var user = repository.GetById(id);
if (ModelState.IsValid)
{
if (user != null)
{
user.Username = model.users.Username;
user.Forename = model.users.Forename;
user.Lastname = model.users.Lastname;
user.Email = model.users.Email;
user.Status = model.users.Status;
user.UserRoleID = Convert.ToInt32(model.UserRoles);
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return View();
}
}
return View();
}
However on Submit it is giving me a Null reference
exception on the dropdownlist as shown below? Now sure why?