I\'m working with ASP.NET MVC 4 and Entity Framework. In my database, I have a table Subscription which represents a subscription to public transports. This
Just an extension to Slauma's answer. In my case i had to represent many-to-many like a table between Products and Roles, first column representing Products, the header representing Roles and the table to be filled with checkboxes to select roles for product. To achieve this i have used ViewModel like Slauma described, but added another model containing the last two, like so:
public class UserViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable Products { get; set; }
}
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable Roles { get; set; }
}
public class RoleViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
Next, in Controller we need to fill data:
UserViewModel user = new UserViewModel();
user.Name = "Me";
user.Products = new List
{
new ProductViewModel
{
Id = 1,
Name = "Prod1",
Roles = new List
{
new RoleViewModel
{
Id = 1,
Name = "Role1",
IsSelected = false
}
// add more roles
}
}
// add more products with the same roles as Prod1 has
};
Next, in View:
@model UserViewModel@using (Ajax.BeginForm("Create", "User",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "divContainer"
}))
{
@foreach (RoleViewModel role in Model.Products.First().Roles.ToList())
{
@role.Name
}
@Html.EditorFor(model => model.Products)
}
As you see, EditorFor is using template for Products:
@model Insurance.Admin.Models.ProductViewModel
@Html.HiddenFor(model => model.Id)
@Model.Name
@Html.EditorFor(model => model.Roles)
This template uses another template for Roles:
@model Insurance.Admin.Models.RoleViewModel
@Html.HiddenFor(model => model.Id)
@Html.EditorFor(model => model.IsSelected)
And voila, we have a table containing first column Products, the header contains Roles and the table is filled with checkboxes. We are posting UserViewModel and you will see that all the data are posted.