CheckBox List in ASP.net MVC3

2019-06-06 16:04发布

问题:

I have an SuperVisor Form and I need to show a list of Employees with checkboxes for selection.

Once I click Save , supervisor information and the selected employees id should be saved to DB.

Which is best option to achieve this ?

回答1:

Model

public class SelectEmployee
{
    public int _EmployeeID;
    public string _EmployeeName;
    public bool _check;

    public int EmployeeID { get { return _EmployeeID; } set { _EmployeeID = value; } }
    public string EmployeeName { get { return _EmployeeName; } set { _EmployeeName = value; } }
    public bool check { get { return _check; } set { _check = value; } }
}
public class DemoManager
{
    public static List<SelectEmployee> GetSelectedEmployee()
    {
        DemoEntities db = new DemoEntities();
        var query = (from i in db.EmployeeMasters
                     select new SelectEmployee { EmployeeID = i.EmployeeID, EmployeeName = i.EmployeeName, check = false }).ToList();
        return query;
    }
}

View

@using(Html.BeginForm()) 
{ 
<table class="table">

@for (var i = 0; i < Model.Count; i++)  {
    <tr>
        <td>
            @Html.DisplayFor(modelEmployee => modelEmployee[i].EmployeeID)
        </td>
        <td>
            @Html.CheckBoxFor(modelEmployee => modelEmployee[i].check)
        </td>
        <td>
            @Html.DisplayFor(modelEmployee => modelEmployee[i].EmployeeName)
        </td>
    </tr>
}       
</table>
    <input type="submit" value="click" />
}

Controller

    public ActionResult Index()
    {

        return View(DemoManager.GetSelectedEmployee());
    }

    [HttpPost]
    public ActionResult Index(List<SelectEmployee> emp)
    {
        var query = (from i in emp
                     where i.check == true
                     select i);
      // Here you can set the insert statements the query will contain only selected items

        return View(model);
    }