获取多个复选框选择和逗号seprated [英] Getting multiple checkboxes selection and seprated with comma

查看:276
本文介绍了获取多个复选框选择和逗号seprated的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有权限的列表,想要使用复选框以选择权限,并通过选中的复选框允许IDS与创建role.i沿着有如下一段code的。
型号

 公共类RoleInsert
    {
        [键]
        公众诠释角色ID {搞定;组; }
        公共字符串角色名{获得;组; }
        公共字符串描述{搞定;组; }
        公共字符串权限{搞定;组; }
    }
 视图模型
公共类ViewModelRole
    {
 公众诠释角色ID {搞定;组; }
        公共角色角色{搞定;组; }
        公共IEnumerable的<&RoleList的GT; RoleList的{搞定;组; }
        公共RoleInsert RoleInsert {搞定;组; }
        公共权限权限{搞定;组; }
        公开名单<&许可GT; {PERMISSIONSLIST获得;组; }
        //公开的IEnumerable<的角色和GT; IRole {搞定;组; }
        公众的IDictionary<字符串,字符串> DynamicLabel;        私人preFlightDbContext preFlightDbContext;
        私人IRoleService roleService;
        私人只读ILabelService labelService;
        私人诠释用户ID;
}
}
视图
@model preFlight.ViewModels.ViewModelRole
@using preFlight.Helpers
@ {HtmlHelpers.getDynamicLabels(Model.DynamicLabel);}
<脚本类型=文/ JavaScript的>
$(文件)。就绪(函数(){
    $('#BTN-GN')。点击(函数(){
        VAR名单= [];
        $('#MyDiv输入:检查')每个(函数(){。
            list.push(this.name);
        });
        //现在的名字包含了所有选中的复选框的名字
        //用它做的东西excamle后与阿贾克斯
        $阿贾克斯({
            网址:'@ Url.Action(创建,角色)',
            输入:POST,
            数据:{参数:list},
            成功:函数(结果){
                警报(成功);
            },
            错误:功能(结果){
                警报(错误!);
            }
        }); //结束阿贾克斯
    });
});
    < / SCRIPT>
    @using(Html.BeginForm())
    {
        @ Html.AntiForgeryToken()
            @ Html.ValidationSummary(真)
        < D​​IV CLASS =dialogModal_header>
            @ Html.CustomLabel(lblTitle,添加新角色)
        < / DIV>
    < D​​IV CLASS =dialogModal_content>
    < D​​IV CLASS =集团形式>
     @ Html.CustomLabel(lblRoleName,角色名称)
     @ Html.EditorFor(M = GT; m.Role.RoleName)
     @ Html.ValidationMessageFor(M = GT; m.Role.RoleName)
    < / DIV>
    < D​​IV CLASS =组Form1的>
  < D​​IV CLASS =组窗口2>
  @ Html.CustomLabel(lblDescription,说明)
   @ Html.TextAreaFor(M = GT; m.Role.Description)
   @ Html.ValidationMessageFor(M = GT; m.Role.Description)
    < / DIV>
   < / DIV>
   < D​​IV CLASS =主要内容>
    < D​​IV CLASS =权限-HD>
         @ Html.CustomLabel(lblPermissions,权限)
    < / DIV>
       < D​​IV ID =MySelection>
        @for(INT I = 0; I< Model.PermissionsList.Count;我++)
         {
        < D​​IV CLASS =权限>
       < D​​IV CLASS =CB>           <输入类型=复选框NAME =标签级=无边际
            ID == IDSVALUE =@ Model.PermissionsList [I] .PermissionId>       < / DIV>
       < D​​IV CLASS =每个内容的>
              @ Model.PermissionsList [I] .PermissionName< / DIV>
            < / DIV>
       }
< / DIV>
        < / DIV>
        < / DIV>
    < D​​IV CLASS =dialogModal_footer>
         @ {
        变种S = Model.DynamicLabel.ContainsKey(btnSubmit按钮)? Model.DynamicLabel [btnSubmit按钮]的ToString():提交;
              }
    <按钮式=提交ID =BTN-GN> @ S< /按钮>
         @ {
        变种C = Model.DynamicLabel.ContainsKey(btnClear)? Model.DynamicLabel [btnClear]的ToString():清除;
              }
        <按钮式=重置ID =BTN-RD> @ C< /按钮>    < / DIV>
    }

下面是我的控制器

 公众的ActionResult的Create()
{
  ViewModelRole viewModelRole =新ViewModelRole();
  viewModelRole.PermissionsList = preDbContext.Permissions.ToList();
  返回查看(viewModelRole);
}[HttpPost]
    公众的ActionResult创建(ViewModelRole viewModelRoleForAdd,串角色名,字符串roledescription,字符串[]标记)
    {
        viewModelRoleForAdd.RoleInsert.RoleName =角色名;
        viewModelRoleForAdd.RoleInsert.Description = roledescription;
        viewModelRoleForAdd.RoleInsert.Permission =标签[];
        会话[ApplicationConstants.CurrentPageId] = 130;
        preCoreModel.User与loggedInUser =新的preCoreModel.User();
        INT的PageId = Convert.ToInt16(会话[ApplicationConstants.CurrentPageId]);
        如果(会话[ApplicationConstants.UserModel]!= NULL)
        {
            与loggedInUser =(preCoreModel.User)会话[ApplicationConstants.UserModel]
        }
        如果(loggedInUser.UserId大于0)
        {
            ViewModelRole viewModelRole =新ViewModelRole(preDbContext,loggedInUser.UserId,的PageId);
            roleService.AddRole(角色名,roledescription,标签[]);
            返回查看(viewModelRole);
        }
        其他
        {
            返回RedirectToAction(签到,帐户,新{面积=});
        }
    }


解决方案

我会建议创建视图模型重新present将要显示和数据的编辑。

查看模型(添加验证为需要的属性)

 公共类PermissionVM
{
  公众诠释ID {搞定;组; }
  公共字符串名称{;组; }
  公共BOOL IsSelected {搞定;组; }
}
公共类RoleVM
{
  [显示(NAME =角色名称)]
  公共字符串名称{;组; }
  公共字符串描述{搞定;组; }
  公开名单< PermissionVM>权限{搞定;组; }
}

控制器

 公众的ActionResult的Create()
{
  RoleVM模式=新RoleVM();
  model.Permissions = preDbContext.Permissions
    。选择(P =>新建PermissionVM()
    {
      ID = p.PermissionId,
      名称= p.PermissionName
    });
  返回查看(RoleVM);
}[HttpPost]
公众的ActionResult创建(RoleVM模型)
{
  如果(!ModelState.IsValid)
  {
    返回查看(模型);
  }
  //初始化数据模型
  从视图模型//地图特性(循环model.Permissions获得所选择的权限(IsSelected =真)
  //保存和重定向
}

查看

  @model RoleVM
@using(Html.BeginForm())
{
  ....
  @ Html.LabelFor(M = GT; m.Name)//不知道什么CustomLabel正在做,但似乎没有必要
  @ Html.TextBoxFor(M = GT; m.Name)
  @ Html.ValidationMessageFor(M = GT; m.Name)
  @ Html.LabelFor(M = GT; m.Description)
  @ Html.TextBoxFor(M = GT; m.Description)
  @ Html.ValidationMessageFor(M = GT; m.Description)
  @for(INT I = 0; I< Model.Permissions.Count;我++)
  {
    < D​​IV CLASS =权限>
      @ Html.CheckBoxFor(M = GT; m.Permissions [I] .IsSelected)
      @ Html.LabelFor(M = GT; m.Permissions [I] .Name点)
      @ Html.HiddenFor(M = GT; m.Permissions [I] .ID)//为回发
    < / DIV>
  }
  <输入类型=提交值=保存/>
}

减code,没有JavaScript的,更灵活地添加显示和验证属性,适当的看法...

i have a list of permissions and want to select the permissions using checkbox and pass the selected checkbox permission ids along with creating the role.i have following piece of code. Model

 public class RoleInsert
    {
        [Key]
        public int RoleId { get; set; }
        public string RoleName { get; set; }
        public string Description { get; set; }
        public string Permission { get; set; }
    }
 view model
public class ViewModelRole
    {
 public int RoleId { get; set; }
        public Role Role { get; set; }
        public IEnumerable<RoleList> RoleList { get; set; }
        public RoleInsert RoleInsert { get; set; }
        public Permission Permission { get; set; }
        public List<Permission> PermissionsList { get; set; }
        //public IEnumerable<Role> IRole { get; set; }
        public IDictionary<string, string> DynamicLabel;

        private PreFlightDbContext preFlightDbContext;
        private IRoleService roleService;
        private readonly ILabelService labelService;
        private int UserId;
}
}
view
@model PreFlight.ViewModels.ViewModelRole
@using PreFlight.Helpers
@{HtmlHelpers.getDynamicLabels(Model.DynamicLabel);}
<script type="text/javascript">
$(document).ready(function() {
    $('#btn-gn').click(function () {
        var list = [];
        $('#MyDiv input:checked').each(function() {
            list.push(this.name);
        });
        // now names contains all of the names of checked checkboxes
        // do something with it for excamle post with ajax
        $.ajax({
            url: '@Url.Action("Create","Role")',
            type: 'POST',
            data: { Parameters: list},
            success: function (result) {
                alert("success");
            },
            error: function (result) {
                alert("error!");
            }
        });   //end ajax
    });
});
    </script>
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)
        <div class="dialogModal_header">
            @Html.CustomLabel("lblTitle","Add New Role")
        </div>
    <div class="dialogModal_content">
    <div class="group-form">
     @Html.CustomLabel("lblRoleName","Role Name")
     @Html.EditorFor(m => m.Role.RoleName)
     @Html.ValidationMessageFor(m => m.Role.RoleName)
    </div>
    <div class="group-form1">
  <div class="group-form2">
  @Html.CustomLabel("lblDescription","Description")
   @Html.TextAreaFor(m => m.Role.Description)
   @Html.ValidationMessageFor(m => m.Role.Description)
    </div>
   </div>
   <div class="main-content">
    <div class="permissions-hd">
         @Html.CustomLabel("lblPermissions","Permissions")
    </div>
       <div id="MySelection">
        @for (int i = 0; i < Model.PermissionsList.Count; i++)
         {
        <div class="permissions">
       <div class="cb"> 

           <input type="checkbox" name="tags" class="no-margin"
            id="=ids" value="@Model.PermissionsList[i].PermissionId" >

       </div>
       <div class="per-content">
              @Model.PermissionsList[i].PermissionName</div>
            </div>
       }
</div>
        </div>
        </div>
    <div class="dialogModal_footer">
         @{
        var s = Model.DynamicLabel.ContainsKey("btnSubmit") ? Model.DynamicLabel["btnSubmit"].ToString() : " Submit";
              }
    <button type="submit" id="btn-gn">@s</button>
         @{
        var c = Model.DynamicLabel.ContainsKey("btnClear") ? Model.DynamicLabel["btnClear"].ToString() : " Clear";
              }
        <button type="reset" id="btn-rd">@c</button>

    </div>
    }

here is my controller

public ActionResult Create()
{
  ViewModelRole viewModelRole = new ViewModelRole();
  viewModelRole.PermissionsList = preDbContext.Permissions.ToList();
  return View(viewModelRole);
}



[HttpPost]
    public ActionResult Create(ViewModelRole viewModelRoleForAdd, string rolename,string roledescription,string[] tags)
    {
        viewModelRoleForAdd.RoleInsert.RoleName = rolename;
        viewModelRoleForAdd.RoleInsert.Description = roledescription;
        viewModelRoleForAdd.RoleInsert.Permission = tags[];
        Session[ApplicationConstants.CurrentPageId] = 130;
        PreCoreModel.User loggedInUser = new PreCoreModel.User();
        int PageId = Convert.ToInt16(Session[ApplicationConstants.CurrentPageId]);
        if (Session[ApplicationConstants.UserModel] != null)
        {
            loggedInUser = (PreCoreModel.User)Session[ApplicationConstants.UserModel];
        }
        if (loggedInUser.UserId > 0)
        {
            ViewModelRole viewModelRole = new ViewModelRole(preDbContext, loggedInUser.UserId, PageId);
            roleService.AddRole(rolename,roledescription,tags[]);
            return View(viewModelRole);
        }
        else
        {
            return RedirectToAction("SignIn", "Account", new { area = "" });
        }   


    }

解决方案

I would suggest creating view models to represent the the data you want to display and edit.

View models (add validation attributes as required)

public class PermissionVM
{
  public int ID { get; set; }
  public string Name { get; set; }
  public bool IsSelected { get; set; }
}
public class RoleVM
{
  [Display(Name = "Role Name")]
  public string Name { get; set; }
  public string Description { get; set; }
  public List<PermissionVM> Permissions { get; set; }
}

Controller

public ActionResult Create()
{
  RoleVM model = new RoleVM();
  model.Permissions = preDbContext.Permissions
    .Select(p => new PermissionVM()
    {
      ID = p.PermissionId,
      Name = p.PermissionName
    });
  return View(RoleVM);
}

[HttpPost]
public ActionResult Create(RoleVM model)
{
  if(!ModelState.IsValid)
  {
    return View(model);
  }
  // Initialize your data model
  // Map properties from the view model (loop model.Permissions to get the the selected permissions (IsSelected = true)
  // Save and redirect
}

View

@model RoleVM
@using (Html.BeginForm())
{
  ....
  @Html.LabelFor(m => m.Name) // Not sure what CustomLabel is doing but seems unnecessary
  @Html.TextBoxFor(m => m.Name)
  @Html.ValidationMessageFor(m => m.Name)
  @Html.LabelFor(m => m.Description)
  @Html.TextBoxFor(m => m.Description)
  @Html.ValidationMessageFor(m => m.Description)
  @for (int i = 0; i < Model.Permissions.Count; i++)
  {
    <div class="permission">
      @Html.CheckBoxFor(m => m.Permissions[i].IsSelected)
      @Html.LabelFor(m => m.Permissions[i].Name)
      @Html.HiddenFor(m => m.Permissions[i].ID) // for post back
    </div>
  }
  <input type="submit" value="Save" />  
}

Less code, no javascript, more flexibility to add display and validation attributes appropriate to the view ...

这篇关于获取多个复选框选择和逗号seprated的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆