Not sure if I’m completely missing something but, I have a typical MVC web application using EF and role based authentication, as such:
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
public IList<Role> UserRoles { get; set; }
}
public class Role
{
public int RoleId { get; set; }
public string Name { get; set; }
public IList<User> RoleUsers { get; set; }
}
Ideally, in the above case, I would like a single edit screen to update a users name that also allows add/delete operations on the users roles, e.g. a form with an input field for the name, a table of the users roles with each row having a delete button, and a role drop down list with an add button.
How would I perform edits on the views model (User) without persisting the role additions/deletions to the database until a save request is issued?
It may be best to think of an Add operation instead. If inserting a new user, how could you build a collection of that users roles without inserting the user first?
Thanks in advance.
After looking into this a bit more, Phil Haacked wrote an article on binding a view model to a list, found here…
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
I could probably have used this approach to have a single form with inputs for the entity properties and a collection of associated inputs bound using the above method for sub objects. Although I imagine this would probably require a duplicate list property for each navigation property on the parent entity, which is a strike for me.
If adding an entity with a collection of complex objects, this method also doesn’t resolve how you might elegantly input all the properties for a complex object on the same view (as the parent entity only exists in memory) – the simplest approach probably being partial views containing the edit forms?
For simplicity, I opted to change the edit view to only edit the basic properties of the entity and have a separate link for sub objects that redirects to the relevant controller, using the User example, an add operation would follow as such:
Edit:
Also, in case this helps anyone else.
I set the
/Role/Indexaction to list all roles by default, however it also accepts a UserId parameter (/Role/Index/{user_id}). When a UserId is specified, the action returns a different view (/Role/IndexForUser) whose data model is theUserentity – it does the same as the defaultIndexview, but only lists roles associated with the user, and displays more contextual links such as ‘remove user from role’.