I’m trying to figure how to properly represent values, process selected and later on edit form display checked items as checked and other possible values as nonchecked.
I already try something but I’m not sure am I on the right track. With using these solution edit form only display checked item, and not showing other non checked.
If you have better solution please share, cause I’m trying to figure how these work.
Here it is: Assume there is User which may belong to one or many Roles. So I would represent these trough two viewmodels, UserViewModel and RoleViewModel
**UserViewModel.cs**
public int id {get; set;}
public string username {get; set;}
public UserViewModel()
{
Roles = new List<RoleViewModel>();
}
public void SendToDomain(User user, ISession nhibSession)
{
if(user.Roles != null)
{
user.Roles.Clear();//Clear previous selected items
foreach(Role role in Roles)
{
if(role.IsInRole)
user.Role.Add(nhibSession.Load<Role>(user.RoleId));
}
}
}
**RoleViewModel**
public bool IsInRole {get; set;}
[HiddenInput(displayValue = false)]
public int RoleId {get; set;}
[HiddenInput(displayValue = true)]
public string RoleName {get; set;}
And inside EditorTemplates I have RoleViewModel.cs
@model Models.RoleViewModel
@Html.CheckBoxFor(m=>m.IsInRole)
@Html.HiddenFor(m=>m.RoleId)
@Html.LabelFor(m=>m.IsInRole, Model.RoleName)
And finally inside Create view I display these like these
@model Models.UserViewModel
<div> User roles </div> <div> @Html.EditorFor(m => m.Roles) </div>
Here’s how to do it:
UserViewModel
FormView
You need to loop on all Roles that exists in your application. Then, create a checkbox that will be linked to your UserViewModel.RolesIdsSelected and compare the values to the current role.RoleId that is printed. If there’s a match, there will be a check.
CheckboxExtensions
When you will post your data, you will have in the UserViewModel.RolesIdsSelected the ids that have been checked by the user. Then, save the change!