0
votes

i cant seem to pass the employee id value from a check box in the Employees.cshtml view to the Delete Post action method. The delete action method returns Delete.cshtml view which renders the Employees.cshtml as that is in an EditorTemplates folder under the Shared folder. When I click submit i cannot seem to pass the IEnumerable of checked @Model.Ids.

What I want to do is delete every entry that has been checked where the checked value is derived in the Employees.cshtml.

Obviously the issue is that the model binding (I think) will be done from the button submit from the Delete.cshtml page, how can I change this?

The Delete action method.

    [HttpGet]
    public ActionResult Delete()
    {
        return View(db2.Employees.ToList());
    }

The Delete Post action method.

    [HttpPost]
    public ActionResult Delete(IEnumerable<int> EmployeeIDToDelete)
    {
        if (EmployeeIDToDelete != null)
        {
            var employeesToDelete = db2.Employees.Where(x => EmployeeIDToDelete.Contains(x.Id)).ToList();

            foreach (var item in employeesToDelete)
            {
                db2.Employees.Remove(item);
            }
            db2.SaveChanges();
            RedirectToAction("Delete");
        }
        return View(db2.Employees.ToList());
    }

My Delete view

@model IEnumerable<MVC_Example2___ADO.Models.Employees>

@{
    ViewBag.Title = "Delete";
}
<html>
<body>
    @using (Html.BeginForm())
    {
        <table align="center">
            <thead>
                <tr>
                    <td>Check</td>
                    <td>Photo</td>
                    <td>Name</td>
                    <td>Gender</td>
                </tr>
            </thead>
            <tbody>
                @Html.EditorForModel()
            </tbody>
        </table>
        <input type="submit" name="submit" value="Delete Entries" />
    }
</body>
</html>

My Employees View

@model MVC_Example2___ADO.Models.Employees

<tr>
    <td><input type="checkbox" name="employeeIdsToDelete" id="employeeIdsToDelete" value="@Model.Id" /></td>
    <td>@Html.Image(@Model.Photo, @Model.AlternateText, 125, 130)</td>
    <td>@Model.FullName</td>
    <td>@Model.Gender</td>
</tr>
1

1 Answers

0
votes

You have named your checkboxes name="employeeIdsToDelete" but the parameter of your POST method is IEnumerable<int> EmployeeIDToDelete (not plural). The names must match.

Note also you should remove id="employeeIdsToDelete" from the input since this is generating duplicate id attributes which is invalid html.