.NET Development Examined

MVC and DataTables Part III Page 4

Monday, December 19, 2011

The form submission of the edit form is handeled by the AjaxCreateOrEdit action.

[HttpPost] public ActionResult AjaxCreateOrEdit(FormCollection formcollection) { //ToDo add your own update/insert actions SampleEmployee employee = new SampleEmployee(); employee.Name = formcollection["Name"]; employee.Email = formcollection["Email"]; employee.Phone = formcollection["Phone"]; if (formcollection["edit-EmployeeID"] != "") { //Existing record to update employee.EmployeeID = Convert.ToInt32(formcollection["edit-EmployeeID"]); employee.DT_RowId = "row-" + employee.EmployeeID; employeeRepository.Update(employee); } else { //New record to insert employee=employeeRepository.Insert(employee); } return Json(employee); }

Since the form method is defined as a “post” (more secure than a get action) we decorate the ActionResult with the [HttpPost] declaration. We define the action to accept the form collection which contains all the form’s inputs. We create a new instance of the class and populate it by calling the variables name collection. This name (“Name”, “Email”, “Phone” in our sample) is the name of the input on the form. Since we are using the same action for both Create and Edits we need to check the EmployeeID form input. If is empty we know this is a new record, otherwise it is an exsiting one to be updated. Finally we return the employee back as a JSON response.

The delete action is simpler:

// // AJAX: /Edit/AjaxDelete/formcollection [HttpPost] public ActionResult AjaxDelete(FormCollection collection) { int id = Convert.ToInt32(collection["delete-EmployeeID"]); //ToDo add your own delete actions employeeRepository.Delete(id); return Json(id); }

Here we accept the same form collection, but we are only interested in the EmployeeID. Once it is found we delete the record and return the ID for processing on the client side.

So there you have it. MVC, DataTables, jQuery, jQueryUI, jQuery Forms, jQuery BlockUI, JSON, and jQuery Validation all working together in harmony. I have included a download below to play with for further investigation. If you look at it you will also notice that I have moved the creation of the sample data into a repository to simplify the controller code. It also maintains the data in session, so edits can be semi-permanent.

So what’s next? My intention was to take this and work it into a T4 template, which could be implemented when triggering the right-click Add/Controller. While I still intend to get to T4 tempting, I think I will make a detour and look at the newly released KendoUI. We’ll see what next year will bring.



Add Comment