All pastes #1522356 Raw Edit

Unnamed

public text v1 · immutable
#1522356 ·published 2009-08-08 22:32 UTC
rendered paste body
// For http://stackoverflow.com/questions/1248183/how-can-i-use-html-checkbox-to-delete-repeating-groups-in-asp-net-mvc

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(FormCollection collection)
        {
            // Model binding:
            var newEmployee = new Models.Employee();
            var newChildren = new List<Models.Child>();
            var childrenToDelete = new List<String>();
            UpdateModel(newEmployee, "Model.Employee");
            UpdateModel(newChildren, "Model.Child");           
            UpdateModel(childrenToDelete, "childrenToDeleteCheckbox");

            // The "Add Child" button was clicked:
            if (collection["button1"] == "Add Child")
            {
                if (collection["AdditionalChild"] != "")
                {
                    // Add the child:
                    newChildren.Add(new Models.Child { Name = collection["AdditionalChild"], Parent = newEmployee.Name } );
                }
                // Follow the ViewModel pattern and return it to the View:
                var employeeChildrenViewModel = new Models.EmployeeAndChildrenViewModel();
                employeeChildrenViewModel.Employee = newEmployee;
                employeeChildrenViewModel.Children = newChildren;

                return View(employeeChildrenViewModel);
            }

            // The "Delete selected children" button was clicked:
            if (collection["button1"] == "Delete selected children")
            {
                foreach (string child in childrenToDelete)
                {
                    if (child == "false") continue;
                    var temp = child;
                    var qResult = (from q in newChildren where q.Name == temp select q).First();
                    newChildren.Remove(qResult);
                }
                // Follow the ViewModel pattern and return it to the View:
                var employeeChildrenViewModel = new Models.EmployeeAndChildrenViewModel();
                employeeChildrenViewModel.Employee = newEmployee;
                employeeChildrenViewModel.Children = newChildren;

                return View(employeeChildrenViewModel);    
            }

            // Add code to actually add the new Employee here...

            return RedirectToAction("Index");
        }