ASP.NET MVC for many client-side models

I have 3 lots of tables: Users -< UserRoles >- Roles. I created my model as follows:

public class User
{
    public int UserId {get; set;};
    public IEnumerable<Role> Roles {get; set;};
}

public class Role
{
    public int RoleId {get; set;};
    public string RoleName {get; set};
}

public class UserDisplayModel
{
    public User User{get; set;};
    public IEnumerable<Role> AllRoles {get; set;}
}

When editing / creating a user, how can I get the checkbox selected for the role in the controller and how to set it in my view?

If I am wrong from the very beginning along the way of creating my model, tell me and help me in how I will do it.

Thank.

+3
source share
2 answers

The key is that you need the appropriate rendering of your collection in the view. First of all, add the Boolean property to the role view data object so that we have something related to our checkbox:

public class Role
{
    public bool IsInRole { get; set; }
    [HiddenInput(DisplayValue = false)]
    public int RoleId { get; set; }
    [HiddenInput(DisplayValue = true)]
    public string RoleName { get; set; }
}

: HiddenInput ( ). User, , - . , :

<%: Html.EditorFor(m => m.Roles) %>

Role, , . Role.ascx /Views/Shared/EditorTemplates. Roles.ascx :

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcApplication5.Controllers.Role>" %>
<%: Html.EditorFor(m => m.IsInRole) %>
<%: Html.EditorFor(m => m.RoleId) %>
<%: Html.EditorFor(m => m.RoleName) %>

, , html :

<input class="check-box" id="Roles_0__IsInRole" name="Roles[0].IsInRole" type="checkbox" value="true" /><input name="Roles[0].IsInRole" type="hidden" value="false" />
<input id="Roles_0__RoleId" name="Roles[0].RoleId" type="hidden" value="1" />
RoleName1<input id="Roles_0__RoleName" name="Roles[0].RoleName" type="hidden" value="RoleName1" />
<input class="check-box" id="Roles_1__IsInRole" name="Roles[1].IsInRole" type="checkbox" value="true" /><input name="Roles[1].IsInRole" type="hidden" value="false" />
<input id="Roles_1__RoleId" name="Roles[1].RoleId" type="hidden" value="2" />
RoleName2<input id="Roles_1__RoleName" name="Roles[1].RoleName" type="hidden" value="RoleName2" />

, ​​. DisplayValue = true , , . roleId, , . . HiddenInput.

, MVC , , , .

+1

. .

0

Source: https://habr.com/ru/post/1769642/


All Articles