将数组中的选定复选框检索到控制器中

时间:2015-11-04 03:33:06

标签: asp.net-mvc-4 checkbox arraylist

如何检索控制器中的所选复选框。

这是用户可以选择请求访问权限的主视图。

@using (Html.BeginForm("addBatch_CARF", "CARF", FormMethod.Post, new { @name = "register" }))
{
    @Html.ValidationSummary(true)
    <div id="formAlert" class="alert alert-danger">  
        <a class="close">×</a>  
        <strong>Warning!</strong> Make sure all fields are filled and try again.
    </div>

    var catName = "";
    var displayCan = "";
    var candidates = "";

    for (int i = 0; i < Model.Count; i++)
    {
        if (catName != Model[i].request_category)
        {
            <li class="list-group-item list-group-item-success">
                @Html.DisplayFor(modelItem => Model[i].request_category)
                <span class="pull-right" style="margin-right:60px;">Special Instructions</span>
            </li>
            catName = Model[i].request_category;
            displayCan = catName;
        }
        if (displayCan == Model[i].request_category)
        {
            candidates = Model[i].request_name;
            <div class="checkbox_request">
                @Html.CheckBoxFor(model => model[i].isSelected, new { @class = "is_selected" })                      
                @Html.DisplayFor(model => model[i].request_name)
                @if(Model[i].request_name == "Folder Access")
                {
                    <span class="label label-danger">Pls specify all the drive path. Note: For accessing of drives outside PETC please proceed to Online CARF</span>
                }
                <span class="pull-right">
                    @Html.EditorFor(model => model[i].special_instruction)
                </span>
                @Html.HiddenFor(model => model[i].request_type_id)
                @Html.HiddenFor(model => model[i].system_roles_id)
            </div>
         }                     
     }
     <li class="list-group-item list-group-item-success">
         Access to:
     </li>                 
     <div id="employeeAdd">
         @{Html.RenderAction("AddRequestor"); }
     </div>                 
     <p class="request_btn">
         <button type="submit" class="btn btn-primary" id="addbtn">Save</button>
     </p>
}

我在选择或添加员工时只提供了此视图AddRequestor

<table class="table table-hover">
    @for (int i = 0; i < Model.Count; i++){
            <tr>
                <th>
                    @Html.CheckBox("checkbox", new { @class = "is_selected" }) 
                    @Html.DisplayFor(model => model[i].FullName)
                    @Html.HiddenFor(model => model[i].Emp_Badge_No)
                </th>
            </tr>    

    }   
</table>

这样做的主要目标是所有被选中的员工也必须拥有所有选择的请求权限。

[HttpPost]
public ActionResult addBatch_CARF(List<Request_Type> list, List<Employees_All_vw> emp, string[] checkboxes)
{
    foreach (var x in emp)
    {
        int num = 1;
        bool z = Convert.ToBoolean(num);
        if (x.checkbox == z)
        {
            //add data into CARF table
            CARF carf = new CARF();
            carf.requestor = x.Emp_Badge_No;
            carf.carf_type = "BATCH CARF";
            carf.created_by = @User.Identity.Name.Remove(0, 9).ToLower();
            carf.created_date = System.DateTime.Now;
            carf.active_flag = true;
            db.CARves.Add(carf);
            db.SaveChanges();
            int id = carf.carf_id;
            //add data into Request Access Table
            foreach (var i in list)
            {
                int val = 1;
                bool y = Convert.ToBoolean(val);
                if (i.isSelected == y)
                {
                    Request_Access ra = new Request_Access();
                    ra.request_access_id = 1;
                    ra.carf_id = id;
                    ra.request_type_id = i.request_type_id;
                    ra.special_instruction = i.special_instruction;
                    ra.ra_assignee = i.system_roles_id;
                    ra.dept_approval = null;
                    ra.dept_approval_date = null;
                    ra.dept_remarks = null;
                    ra.final_approval = null;
                    ra.final_approval_date = null;
                    ra.final_remarks = null;
                    ra.acknowledge_by = null;
                    ra.acknowledge_date = null;
                    ra.journal = null;
                    ra.closed_by = null;
                    ra.closed_date = null;
                    ra.verified_by = null;
                    ra.verified_date = null;
                    db.Request_Access.Add(ra);
                }
            }
            db.SaveChanges();
        }
        TempData["MessageAlert"] = "Successfully created!";
        return RedirectToAction("Batch_CARF");
    }
}

我在这一行if (x.checkbox == z)

上收到错误
  

运算符'=='不能应用于'string []'和'bool'类型的操作数

1 个答案:

答案 0 :(得分:1)

您的参数string[] checkboxes包含string类型的值("True""False"),因此您需要在比较之前使用Convert.ToBoolean()方法{ {1}}。但是,这不起作用,因为if (x.checkbox == z)生成了2个输入@Html.CheckBox("checkbox", ..) type="checkbox"value="True" type="hidden"所以如果选中它,value="False"true false发回,如果未选中,则仅发布false。您无法匹配哪些值属于哪个员工。

而是创建一个视图模型来表示员工的选择

public class EmployeeVM
{
  public string BadgeNumber { get; set; }
  public string Name { get; set; }
  public bool IsSelected { get; set; }
}

然后在您的AddRequestor()方法中(假设您有一个Employees表)

public ActionResult AddRequestor()
{
  List<EmployeeVM> model = db.Employees.Where(e => e.active_flag).Select(e => new EmployeeVM
  {
    BadgeNumber = e.Emp_Badge_No,
    Name = e.FullName
  }.ToList();
  return PartialView(model);
}

并在视图中

@model List<EmployeeVM>
@for (int i = 0; i < Model.Count; i++)
{
  @Html.HiddenFor(m => m[i].BadgeNumber)
  <label>
    @Html.CheckboxFor(m => m[i].IsSelected)
    <span>@Html.DisplayFor(m => m[i].Name)</span>
  </label>
}

最后,在POST方法中

[HttpPost]
public ActionResult addBatch_CARF(List<Request_Type> list, List<EmployeesVM> employees)
{
  // To get the selected employees
  IEnumerable<string> selectedEmployees = employees.Where(e => e.IsSelected);
  foreach(EmployeesVM employee in selectedEmployees)
  {
    ....
    carf.requestor = employee.BadgeNumber;
    ....