获取多个复选框选择并用逗号分隔 [英] Getting multiple checkboxes selection and separated with comma

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

问题描述

我有一个权限列表,并且想要使用复选框选择权限,并在创建角色的同时传递选定的复选框权限ID。我有以下代码。
模型

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>
    }

这是我的控制人

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; }
}

控制器

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
}

查看

@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" />  
}

缺少代码,没有javascript,可以更灵活地添加适合的显示和验证属性视图...

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

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

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