Been at this for too long! any advice on the following problem…
code added:
Model: AccountModels.cs
[Required]
[Display(Name = "Select role: ")]
public String Role { get; set; }
Controller: AccountController.cs
// GET: /Account/Register
public ActionResult Register()
{
List<SelectListItem> list = new List<SelectListItem>();
SelectListItem item;
foreach (String role in Roles.GetAllRoles())
{
item = new SelectListItem { Text = role, Value = role };
list.Add(item);
}
ViewBag.roleList = (IEnumerable<SelectListItem>)list;
return View();
}
Also in the [HTTpPost]
if (createStatus == MembershipCreateStatus.Success)
{
Roles.AddUserToRole(model.UserName, model.Role);
MailClient.SendWelcome(model.Email);
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
return RedirectToAction("Create", "Customers");
}
View: Register.cshtml
<div class="editor-label">
@Html.LabelFor(m => m.Role)
</div>
<div class="editor-field">
@Html.DropDownListFor(m => m.Role, ViewBag.roleList as IEnumerable<SelectListItem>)
The code works and allows the user to select a role but falls apart if the user breaks validation rules when creating a new account.
Example: if the passwords don’t match normally validation would kick in but due to the addition of the new code the application just crashes.
The code which creates the error:
@Html.DropDownListFor(m => m.Role, ViewBag.roleList as IEnumerable<SelectListItem>)
Error code
The ViewData item that has the key ‘Role’ is of type ‘System.String’ but must be of type ‘IEnumerable’.
I guess you have this problem occuring when in your HttpPost action method where your Validation fails. and i believe you have
return View()statement in your HttpPost action method. When you return the View again, your ViewData is null. So you need to reload the data again for the dropdownIdeally, I would not use the ViewData to hande this. I will have my ViewModel to handle this.
and in your get action call,pass the ViewModel back to your View.
Make your View a strongly typed one
and in your HttpPostAction, Receive this ViewModel object as the parameter