views:

30

answers:

1

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?

A: 

You could store it in TempData.

TempData["UserRoles"] = Model.Roles;

That said, I tend to shy away from keeping data between requests. Ask yourself seriously how much of a drain it would be to go back to the database.

pdr
Well ideally the collection I want to keep between requests would be passed the same way as the rest of the model (using http parameters). I was just wondering if it's possible to do this (maybe serializing the data to the with the MVC 2 Futures "view state" feature and using model binder to deserialize it or maybe serialize using JSON). That would be a cleaner way to do this wouldn't it?I'll do some tests later on and post my results.
brainnovative
Why would you want to pass data to the client that is just going to get sent back as part of the form? I mean you can - just use a hidden field - but I can't understand why you'd want to
pdr
well since it resides in the administration area and this would not be used often I will accept the small overhead of fetching the results from DB again.
brainnovative