Martin Doms
Martin Doms

Reputation: 8748

How do I add relational data to an ASP.net MVC data entity Create view?

Let's say I have a table of staff members, and a separate table of staff roles in a many-to-many relationship (ie, with a StaffMembersInRoles table in between). Using the ADO.net entity framework we have an object model like this: alt text http://martindoms.com/img/datamodel.png

I have a StaffController controller with a create method and a Create view which is pretty much the standard automatically generated type. I want the create page to list the roles in the StaffRoles table with a checkbox next to each, and when the submit button is pressed these are added to the new StaffMember StaffRole IEnumable (and so the appropriate entries are made in the StaffMembersInRoles table). How would I go about this with a strongly-typed view?

Upvotes: 2

Views: 697

Answers (2)

alexl
alexl

Reputation: 6851

Hi the Problem with this approach is you don't really have a strongly type entity passed to the View. In this problem you need the StaffMember information and a list of all StaffRole entities. PS: I really dun like the approach of casting the list in the view : StaffRole[])ViewData["AllRoles"]

Basicly i will prefer to work with DTO.

DTO:

public StaffMemberDto
{ 
    public int StaffMemberId { get; set; }
    public IList<StaffRoleDto> AllStaffRoles { get; set;}
    public IList<StaffRoleDto> MembersRolesAttached  { get; set;}
}

public StaffRoleDto
{
    public int RoleId {get; set;}
    public string RoleName { get; set; }
}

Controller:

return View(StaffMemberDto);

So in the view you get all roles strongly typed:

foreach (var role in ViewDate.Model.AllStaffRoles)
{
    ...
}

And in the post you can send the StaffMemberDto with the good RoleDto already assigned in the view or you can do the Request trick to get the id of the checkboxes ticked.

Well in a view like this i will probably use jquery to request an addRole each time someone tick the box to add a role. It will add some ajax to your form and you will not have some postback.

Upvotes: 1

Chris
Chris

Reputation: 40661

This is how i'd do it:

Firstly, you need an array of all possible roles. In the controller, i'd do something like this (i'm making some assumptions about your DAO):

ViewData["AllRoles"] = (StaffRole[])StaffRole.FindAll();

Then in your view, loop through the roles:

<% foreach (StaffRole Role in (StaffRole[])ViewData["AllRoles"]) { %>

 <p>
  <label>
   <%= Html.CheckBox("Role_"+Role.RoleId.ToString()) %>
   <%= Html.Encode(Role.RoleName) %>
  </label>
 </p>

<% } %>

Then in your POST controller, do something like this:

foreach (StaffRole Role in (StaffRole[])StaffRole.FindAll())
{
  if (Request.Params["Role_"+Role.RoleId.ToString()]=="true")
    MyStaff.Roles.Add(Role);
}

Upvotes: 4

Related Questions