Retain a list of objects and pass it to the create/edit view when validation fails in ASP.NET MVC 2
- by brainnovative
I am binding a Foreign key property in my model. I am passing a list of possible values for that property in my model. The model looks something like this:
public class UserModel
{
public bool Email { get; set; }
public bool Name { get; set; }
public RoleModel Role { get; set; }
public IList<RoleModel> Roles { get; set; }
}
public class RoleModel
{
public string RoleName
{
get;
set;
}
}
This is what I have in the controller:
public ActionResult Create()
{
IList<RoleModel> roles = RoleModel.FromArray(_userService.GetAllRoles());
UserModel model = new UserModel()
{
Roles = roles
};
return View(model);
}
In the view I have:
<div class="editor-label">
<%= Html.LabelFor(model => model.Role) %>
</div>
<div class="editor-field">
<%= Html.DropDownListFor(model => model.Role, new SelectList(Model.Roles, "RoleName", "RoleName", Model.Role))%>
<%= Html.ValidationMessageFor(model => model.Role)%>
</div>
What do I need to do to get the list of roles back to my controller to pass it again to the view when validation fails. This is what I need:
[HttpPost]
public ActionResult Create(UserModel model)
{
if (ModelState.IsValid)
{
// insert logic here
}
//the validation fails so I pass the model again to the view for user to update data but model.Roles is null :(
return View(model);
}
As written in the comments above I need to pass the model with the list of roles again to my view but model.Roles is null. Currently I ask the service again for the roles (model.Roles = RoleModel.FromArray(_userService.GetAllRoles());) but I don't want to add an extra overhead of getting the list from DB when I have already done that..
Anyone knows how to do it?