获取多个复选框并使用逗号分隔

时间:2014-11-25 10:09:01

标签: asp.net-mvc-4 checkbox

我有一个权限列表,并希望使用复选框选择权限,并传递选中的复选框权限ID以及创建角色。我有以下代码段。 模型

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


    }

1 个答案:

答案 0 :(得分:0)

我建议创建视图模型来表示要显示和编辑的数据。

查看模型(根据需要添加验证属性)

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,更灵活地添加适合视图的显示和验证属性...

相关问题