Getting multiple checkboxes selection and separated with comma

可紊 提交于 2020-01-16 00:17:28

问题


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 = "" });
        }   


    }

回答1:


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



来源:https://stackoverflow.com/questions/27123817/getting-multiple-checkboxes-selection-and-separated-with-comma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!