Ajax Datatables Cannot Read Property Length of Undefined

This commodity shows how a datatable with standard Grime functionalites (select/delete information, update single jail cell, and add new record) tin be created in ASP.NET MVC using the jQuery DataTables Editable plug-in.

  • Download source lawmaking - 262.v KB

Table of Content

  1. Introduction
  2. Background
  3. Using the Code
    1. Model
    2. View
    3. Controller
  4. Example - Implementation of Crud Actions
    1. Updating Cells
    2. Deleting Rows
    3. Calculation Records
  5. Configuration in the Server Side Processing Mode
  6. Total Customization
    1. Setting action URLs
    2. Configure DOM
    3. Customize Error Letters
    4. Custom Column Editors
  7. Summary
  8. History

Introduction

The purpose of this article is to show how you lot can implement a table with the full prepare of data management functionalities in ASP.NET MVC using jQuery/AJAX with various plug-ins. Here is a list of the aimed functionalities:

  1. Client side pagination, filtering, sorting
  2. Crud operations - deleting/editing/calculation records
  3. Constructive client-side functionalities where nearly of the interaction is done by AJAX

My intention is to bear witness how y'all can implement these functionalities with minimal effort using a jQuery DataTables Editable plug-in and thereby easily extending DataTable Grime functionalities. Example of such kind of table is shown in the figure below:

MVC-CRUD-DataTable/datatables_edit_cell.png

All functionalities you see in the figure are pure JavaScript enhancement - on the server-side, you lot only need to generate a pure HTML tabular array. Everything you see in the table is implemented on the customer-side using the following JavaScript phone call:

$('          table#myDataTable').dataTable().makeEditable();

This line of code finds a table with id "myDataTable", and applies two JQuery plugins that add to the table all functionalities shown above. In the rest of the article, I volition show you how you lot can implement and customize this plugin.

This article might be considered as a second part in the serial of articles that describes how to implement effective Web ii.0 interfaces with jQuery, ASP.Internet MVC, and the jQuery DataTables plugin. In my previous commodity, I described how you tin implement a DataTable with server-side pagination, filtering, and sorting which enables you lot to implement high-performance table operations. In this article, server-side actions are not described again, and focus is on the data management functionalities simply. These two articles can help you to create effective Web 2.0 data tables with fully AJAXified functionalities.

Background

A common requirement in web projects is to create a table where also listing data, the user should be able to edit data, and add together new or delete existing records. When a fully functional information table/information grid needs to be implemented, my selection is the jQuery DataTables plug-in. This plug-in takes a plainly HTML tabular array and adds several functionalities such every bit pagination, ordering by column, filtering by keyword, changing the number of records that should be displayed per page, etc. All you need to exercise is to include a single JavaScript call:

<script language="          javascript"          type="          text/javascript">     $(certificate).ready(function          () {         $('          #myDataTable').dataTable();     });   </script>        

In the instance, myDataTable is the ID of the table that should exist enhanced with the DataTables plug-in. Full description of the jQuery DataTables features can exist establish hither. The pic that follows shows a plain HTML table after applying the DataTables plug-in.

MVC-CRUD-DataTable/datatables.png

DataTables itself provides a very good API for data manipulation (adding rows, deleting rows, etc.). However, a drawback is that you volition need to learn the API functions and implement Grime functionalities yourself considering there is no out-of-the-box solution that enables yous to hands implement CRUD functionalities. This might brand 1 think of moving from DataTables to some other plug-in such equally jqGrid (which is also a practiced plug-in, similar to DataTables) just because information technology has out-of-the-box configuration for Crud functionalities. Therefore, my goal was to encapsulate the jQuery DataTables functionalities that are needed for the standard CRUD operations into a split plug-in which adds CRUD functionalities on height of the standard ready of DataTables functionalities and makes it possible for a developer to activate it as hands every bit possible. Code to initialize an editable data table is shown below:

<script language="          javascript"          type="          text/javascript">     $(document).ready(role          () {         $('          #myDataTable').dataTable().makeEditable();     });   </script>

This line of code would outcome in a table that allows the user to edit data past double clicking on a cell, select and delete any row in the table, and add a new record. An instance of the enhanced table tin can be found on the alive demo site. Beside this, you'll need to create server-side lawmaking that accepts AJAX calls sent by the plug-in when the user changes some record and this article volition guide you through this chore.

Using the Lawmaking

For illustrative purposes, we'll use a simple ASP.NET MVC spider web application to list companies, delete them, add together new or update existing visitor data. The first thing you lot need to do is to create a standard ASP.Internet Model-View-Controller construction. There are three steps required for this setup:

  1. Creating the model classes that represent the information structure that volition be shown
  2. Creating the controller class that will react on the user events
  3. Creating the view that will render data and create HTML code that is sent to the browser window

In the start, nosotros'll only brandish company data in a table. Then, this simple table volition be enhanced with the jQuery DataTables Editable plug-in. The following JavaScript components need to exist downloaded:

  1. jQuery library v1.4.4., containing standard classes used by the DataTables plug-in
  2. jQuery UI library v1.eight.vii., containing classes for handling dialogs
  3. jQuery DataTables plug-in v1.vii.5., including the optional DataTables CSS style-sheets used for applying the default styles on the page
  4. jQuery Jeditable plug-in v1.half-dozen.two., required for inline jail cell editing
  5. jQuery validation plug-in v1.7., for implementation of client-side validation
  6. jQuery DataTables Editable plug-in that integrates all these mentioned plug-ins into a fully functional editable datatable.

These files should exist stored in the local file system and included in the HTML page that is rendered on the customer. Example of usage of these files is explained below.

Model

The model comes to a simple course containing company information. The fields that we need are company ID, proper name, address, and a boondocks. The source code for the company model class is shown below:

          public          class          Company {          public          int          ID {          get;          set; }          public          string          Name {          get;          set; }          public          string          Accost {          become;          set; }          public          string          Town {          become;          gear up; } }

View

View is used to render data on the server-side and send HTML lawmaking to the browser. The example includes iii unlike view pages that evidence different usage and configuration of the plug-in. There'south one layout page that will exist used past all these pages. This layout folio is shown below:

          <          !DOCTYPE                              html          >          <          html          >          <          head          >          <          championship          >Customization of Editable DataTable<          /title          >          <          link                              href          ="          @Url.Content("          ~/Content/dataTables/demo_table.css          "          )          "                              rel          ="          stylesheet"                              type          ="          text/css"                              /          >          <          link                              href          ="          @Url.Content("          ~/Content/dataTables/demo_table_jui.css          "          )          "                              rel          ="          stylesheet"                              type          ="          text/css"                              /          >          <          link                              href          ="          @Url.Content("          ~/Content/themes/base/jquery-ui.css          "          )          "                              rel          ="          stylesheet"                              type          ="          text/css"                              media          ="          all"                              /          >          <          link                              href          ="          @Url.Content("          ~/Content/themes/smoothness/jquery-ui-1.7.2.custom.css          "          )          "                              rel          ="          stylesheet"                              type          ="          text/css"                              media          ="          all"                              /          >          <          script                              src          ="          @Url.Content("          ~/Scripts/jquery-one.four.4.min.js          "          )          "                              type          ="          text/javascript"          >          <          /          script          >          <          script                              src          ="          @Url.Content("          ~/Scripts/jquery.dataTables.min.js          "          )          "                              blazon          ="          text/javascript"          >          <          /          script          >          <          script                              src          ="          @Url.Content("          ~/Scripts/jquery.jeditable.js          "          )          "                              type          ="          text/javascript"          >          <          /          script          >          <          script                              src          ="          @Url.Content("          ~/Scripts/jquery-ui.js          "          )          "                              blazon          ="          text/javascript"          >          <          /          script          >          <          script                              src          ="          @Url.Content("          ~/Scripts/jquery.validate.js          "          )          "                              blazon          ="          text/javascript"          >          <          /          script          >          <          script                              src          ="          @Url.Content("          ~/Scripts/jquery.dataTables.editable.js          "          )          "                              type          ="          text/javascript"          >          <          /          script          >          @RenderSection("caput", required: false);          <          /head          >          <          body          >          <          div                              id          ="          container"          >          <          a                              href          ="          /Company/Index"          >Basic Example<          /a          >          <          a                              href          ="          /Company/Ajax"          >Getting data with Ajax<          /a          >          <          a                              href          ="          /Visitor/Customization"          >Customization<          /a          >          @RenderBody()          <          /div          >          <          /trunk          >          <          /html          >        

This layout folio does not accept any presentation logic - it but includes all the necessary JavaScript files and contains links to all the pages used in this example. Page specific content will exist rendered when the @RenderBody() call is executed. In improver, this layout page allows you to include custom JavaScript that is specific to the pages in the "head" department. Note that the last JavaScript file is the DataTables Editable plug-in which covers the Grime functionalities that will be presented in this example. The layout page is non required for your projects, but it allows to simplify the views so that they incorporate only code that is relevant for the examples. The view that renders the tabular array is shown in the listing below:

@{     Layout = "~/Views/Company/JQueryDataTableEditableLayout.cshtml"; }  @section caput{          <          script                              language          ="          javascript"                              type          ="          text/javascript"          >          $(document).ready(function          () {                 $('          #myDataTable').dataTable().makeEditable();             });          <          /          script          >          }          <          div                              id          ="          demo"          >          <          h1          >Basic Example<          /h1          >          <          table                              id          ="          myDataTable"                              course          ="          display"          >          <          thead          >          <          tr          >          <          th          >Company name<          /th          >          <          th          >Address<          /th          >          <          th          >Boondocks<          /th          >          <          /tr          >          <          /thead          >          <          tbody          >          @foreach (var particular in Model)             {          <          tr                              id          ="          @particular.ID"          >          <          td          >@particular.Name<          /td          >          <          td          >@item.Address<          /td          >          <          td          >@item.Town<          /td          >          <          /tr          >          }          <          /tbody          >          <          /table          >          <          div                              class          ="          add_delete_toolbar"                              /          >          <          /div          >        

This view uses the layout page described in a higher place, and puts the initialization JavaScript in the header that initializes the data table and makes it editable. The trunk contains a tabular array with a company name, address, and town. The ID of each company is placed in an ID attribute of the surrounding <tr> tag - this is a place where the DataTables Editable plug-in expects to observe the ID of the record that volition exist edited or deleted. Also, in that location is a <div> element with a form "add_delete_toolbar" which tells the DataTables Editable plug-in where it should place the auto-generated add and delete buttons.

Controller

When a folio is required past the user, the controller returns a company listing that volition be rendered in the view. Instead of a database, at that place is the DataRepository grade that just returns a list of all the companies. An example of the controller with one action method that reacts to the /Company/Alphabetize request is shown beneath:

          public          class          CompanyController : Controller {          public          ActionResult Alphabetize()         {          var          companies = DataRepository.GetCompanies();          return          View(companies);         } }

When the "/Company/Alphabetize" request is sent from the client, this activity method is executed and a fix of all the companies from the repository is sent to the view.

The just thing yous demand to do is to create server-side deportment that handle the add, delete, and update requests sent by the plug-in. These actions can be added as controller actions:

          public          class          CompanyController : Controller {          public          string          DeleteData(int          id){ ... }          public          string          UpdateData(int          id,          cord          value,          int? rowId,          int? columnPosition,          int? columnId,          cord          columnName){ ... }          public          int          AddData(cord          proper noun,          cord          address,          string          town,          int? land){ ... } }

The DeleteData activeness accepts the ID of the deleted row every bit a parameter and returns an "ok" cord if the update is successful. Any other string value represents an error bulletin that will be shown to the user.

The UpdateData action accepts the ID of the updated cell, a value entered by the user, and the position of the cell (column and row ID). The action should render text equal to the value input parameter. Whatsoever other string value represents an error bulletin that will exist shown to the user.

The AddData action has custom parameters representing all the information that should be saved when a new record is added. The given example uses the name, address, boondocks, and country in the new company record, but in the other implementations, you will utilize arbitrary parameters, so you will need to create a custom form for calculation a new record. The DataTables Editable plug-in handles opening your custom form in the dialog and posting form values to the server-side action shown above.

In the side by side section, I will explain how this plug-in is integrated in the example attached to this article.

Example - Implementation of the Controller Activeness Methods

The code described in the previous sections is necessary for rendering data and initializing the DataTables Editable plug-in. Once it'due south initialized, the plug-in allows y'all to perform the post-obit functionalities:

  1. Updating cell values - When the user double clicks on a jail cell, information technology will be converted into a textbox and when the user finishes editing data and presses Enter, an AJAX telephone call will be sent to the server-side.
  2. Deleting rows - When the user selects a row and presses the Delete push, an AJAX asking will exist sent to the server and then the selected tape tin can be deleted on the server-side.
  3. Adding a new row - When the user adds a new row, an AJAX request is sent with the information about the new record.

The picture below shows the trace of AJAX calls that are sent to the server when these operations are performed by the user. The actions "DeleteData", "AddData", and "UpdateData" are the default AJAX URLs that are called by the plug-in and can be modified if necessary.

MVC-CRUD-DataTable/Ajax_trace.png

The following sections describe the implementation of the needed server-side actions that actually perform these operations on the real data.

Updating Cells

Updating cells is washed past using an inline editable plug-in called Jeditable. The DataTables Editable plug-in is internally configured to supercede the prison cell content with an editable textbox when the user double clicks on the cell. The following figure shows how the user can edit data:

MVC-CRUD-DataTable/datatables_edit_cell.png

When the user finishes cell editing and presses Enter, the plug-in sends the AJAX phone call with the data virtually the edited value. The new cell content is sent to the server with a new value, the ID of the tape, and the coordinates of the cell. The AJAX call that is sent to the server-side is shown beneath:

MVC-CRUD-DataTable/update_data_ajax_request.png

The AJAX asking contains the following parameters:

  1. id of the row taken from the ID attribute of the <tr> tag that surrounds the cell that has been edited. Use this value to find a record that should be updated.
  2. value that is entered in the jail cell. This value should be written in the company record.
  3. columnName - proper noun of the column (e.thousand., text plant in the column heading). You tin can employ this information to make up one's mind which belongings should be updated.
  4. rowId from the tabular array. If ten rows are shown per folio, this volition exist a value between 0 and 9.
  5. columnPosition - position of the cavalcade value from 0 to the number of columns yous run across in the table - one. Hidden columns are non counted. This value tin can exist used instead of the cavalcade name to place the property that should be updated. Use this value if names of the columns tin can exist dynamically changed.
  6. columnId - ID of the column from 0 to the total number of columns - 1. Hidden columns are counted. This value can be used instead of the column proper name to identify the property that should exist updated. Yous should use columnId instead of columnPosition if you lot have hidden columns in the table (either initially hidden or dynamically subconscious).

You volition besides need a controller action that will accept the request described above, receive data sent from the plug-in, update actual data, and return response. Example:

          public          grade          CompanyController : Controller {                                                               public          string          UpdateData(int          id,          string          value,          int? rowId,          int? columnPosition,          int? columnId,          string          columnName)     {          var          companies = DataRepository.GetCompanies();          if          (columnPosition ==          0          && companies.Whatsoever(                   c => c.Proper name.ToLower().Equals(value.ToLower())))          return          "          Visitor with a proper noun '"          +          value          +          "          ' already exists";          var          company = companies.FirstOrDefault(c => c.ID == id);          if          (visitor ==          zero)         {          return          "          Visitor with an id = "          + id +          "                      does not exists";         }          switch          (columnPosition)         {          case          0:                 company.Name =          value;          suspension;          case          1:                 company.Address =          value;          break;          case          2:                 company.Town =          value;          intermission;          default:          break;         }          return          value;     } }

This action accepts data about the ID of the updated record, the iD of the row where the updated prison cell is placed, and ID, position, and proper noun of the cavalcade where the updated prison cell is placed. The code is uncomplicated. The company is plant by using the ID, and i of the backdrop of the constitute record is updated depending on the position of the column. Instead of the cavalcade position, cavalcade proper name can be used - it depends on the server-side logic. If everything is fine, the returned value should exist the same as a value sent by the plug-in in the request. Otherwise, the DataTables Editable plug-in will assume that the update has failed and that the returned text is an error message that should be shown to user. Hence, to notify the plug-in that an error occurred, the only thing y'all need to do is to render an fault message (as shown in the example).

Deleting Rows

The DataTables Editable plug-in enables row selection and initializes a delete button. When the user selects a row, the delete button gets enabled, and later on it'south pressed, an AJAX request with an ID of the currently selected row will be sent to the server. The ID is taken from the id attribute of the <tr> tag. The AJAX request that is sent by the plug-in to the server-side folio is shown below:

MVC-CRUD-DataTable/delete_data_ajax.png

The server-side folio should return an "ok" string if the tape is successfully deleted, or an error message that should be shown to the user.

The Controller action that accepts an ID of the row that needs to be deleted and actually deletes a row is given in the following example:

          public          course          CompanyController : Controller {                                   public          string          DeleteData(int          id)     {          try          {          var          company =                   DataRepository.GetCompanies().FirstOrDefault(c => c.ID == id);          if          (company ==          null)          return          "          Company cannot exist institute";             DataRepository.GetCompanies().Remove(visitor);          render          "          ok";         }          catch          (Exception ex)         {          render          ex.Bulletin;         }     } }

If everything is fine, an "ok" string is returned back. Whatever other cord that is returned from the code such every bit "Company cannot be establish" or an exception message will exist shown on the client-side as an error message, and deleting will be cancelled.

Calculation New Records

Adding a new record is a bit complicated - in this instance, it is not plenty simply to add i action in the controller. For adding a new record, information technology is necessary to add an HTML form that will exist used for calculation a new tape. This class should have the id "formAddNewRow" and should contain the input elements that the user needs to populate. An example of the form is shown in the listing below:

          <          form                              id          ="          formAddNewRow"                              activity          ="          #"                              title          ="          Add new company"          >          <          label                              for          ="          name"          >Name<          /label          >          <          input                              type          ="          text"                              name          ="          proper noun"                              id          ="          name"                              course          ="          required"                              rel          ="          0"                              /          >          <          br                              /          >          <          label                              for          ="          name"          >Address<          /characterization          >          <          input                              type          ="          text"                              name          ="          accost"                              id          ="          address"                              rel          ="          one"                              /          >          <          br                              /          >          <          label                              for          ="          name"          >Postcode<          /characterization          >          <          input                              type          ="          text"                              name          ="          postcode"                              id          ="          postcode"          /          >          <          br                              /          >          <          characterization                              for          ="          name"          >Boondocks<          /label          >          <          input                              type          ="          text"                              name          ="          town"                              id          ="          town"                              rel          ="          two"                              /          >          <          br                              /          >          <          label                              for          ="          name"          >Country<          /label          >          <          select                              name          ="          country"                              id          ="          country"          >          <          option                              value          ="          ane"          >Serbia<          /choice          >          <          option                              value          ="          two"          >France<          /option          >          <          option                              value          ="          iii"          >Italy<          /option          >          <          /select          >          <          br                              /          >          <          /form          >        

When the DataTables Editable plug-in detects the Adding new record course, the "Add together" button will be auto-generated. When a user presses the "Add together" push button, the DataTables Editable plug-in opens a form in the new dialog window where the user tin can enter information about the new record (the dialog is shown below).

MVC-CRUD-DataTable/datatables_add_new.png

This form cannot be auto-generated because I assume that in each add functionality, you will need some custom form with various elements such as textboxes, calendars, etc. Therefore, I assume that it will exist easier that you add a plain HTML class that suits you best and style it, rather than apply some auto-generated functionality. In this form, it is important to add together rel attributes to the input elements that should be copied to the table when a record is added. The rel attributes are used by the DataTable Editable plug-in to map values of the new record with the columns in the table. In the example given to a higher place, the values that will be entered in the name, address, and town inputs will be mapped to the columns 0, 1, and two of the tabular array - rel attributes are used for this mapping.

As information technology tin can be seen, OK and Cancel buttons do non demand to be added in the class - the DataTables Editable plug-in adds them automatically as the last elements in the form. The form is automatically validated on the client-side using a jQuery validation plug-in. Therefore, you tin can add together the "required", "email", "date", and other CSS classes to automatically implement customer-side validation. In the higher up instance, name is marked as required field and a client-side fault message will be shown if this field is not populated. You tin see what validation rules can be used on the jQuery validation plug-in site. When the DataTables Editable plug-in detects the "Add new record" grade, it volition enable the user to add a new record via that form and post elements found in the form to the server-side. When the user presses the "OK" button, an AJAX request is sent to the server and if everything is fine, the dialog is closed and a new row is added to the table. An example of the AJAX request that is sent from the form displayed in a higher place is shown on the post-obit figure:

MVC-CRUD-DataTable/add_data_ajax.png

The AJAX call sends all the values of the input elements in the form and expects to become the ID of the new row back. Once the ID is returned, the new row is added, populated with the values from the grade, and the returned ID of the record is fix as an ID aspect of the new row.

DataTables Editable handles common operations such every bit opening a dialog, posting a asking to the server, closing a dialog when Abolish is pressed, and calculation a row in the table if an performance is successful. The only matter that needs to exist done is creating a plain HTML form as a template for adding a new record, and a server-side action that accepts information about the new tape.

The Controller action that accepts the information entered in the class is shown below:

          public          class          CompanyController : Controller {          public          int          AddData(cord          name,          string          address,          cord          town,          int          country)     {          var          companies = DataRepository.GetCompanies();          if          (companies.Any(c => c.Name.ToLower().Equals(name.ToLower())))         {             Response.Write("          Visitor with the proper noun '"          + name +          "          ' already exists");             Response.StatusCode =          404;             Response.End();          render          -i;         }          var          visitor =          new          Company();         company.Name = proper name;         company.Accost = address;         company.Town = town;         companies.Add together(company);          return          visitor.ID;     } }

The signature of the method depends on the form parameters - for each parameter that is posted to the server, one argument in the method should be added. As the name, address, town, and country are posted from the client, these parameters are added in the method phone call. The Action method returns an integer value that represents the ID of the new record. If whatsoever error occurs (such equally indistinguishable name constraint violation every bit shown in the example), an fault message should exist returned every bit a response text. Also, the condition lawmaking of the response should exist set to some HTTP error condition. The actual value is irrelevant however, information technology is necessary to return some of the condition codes in the 4xx or 5xx family to notify the DataTables Editable plug-in that the mistake occurred while trying to add together a tape. In this case, I used a 404 error message just the actual code is irrelevant - the only thing that is needed is that the plug-in detects that the error occurred and that it shows the response text to the user.

Configuration in the Server-Side Processing Mode

The DataTables plug-in can use either a row in the table as a source of data or it can be configured to use a JSON source from the server-side page. In the server-side mode, only information that should be shown on the electric current page is returned from the server and displayed in the tabular array. The standard DataTables functionalities such equally filtering, ordering, and pagination merely forward the asking to the server-side where the information is candy and returned back to the DataTables plug-in. This mode requires some server-side development but can significantly increase the performance. The DataTables Editable plug-in can detect whether the DataTables plug-in is used in server-side mode and back up AJAX based functionalities. In this department, I will testify you lot what modifications should be done in the DataTables Editable plug-in to work in this fashion.

Model

In the server-side mode, the model is non changed - the aforementioned company class is used as in the previous case.

View

I accept created a unlike view page that renders the output to match the DataTables AJAX mode. The view is shown below:

@{     Layout = "~/Views/Visitor/JQueryDataTableEditableLayout.cshtml"; }  @section head{          <          script                              linguistic communication          ="          javascript"                              type          ="          text/javascript"          >          $(document).ready(office          () {         $('          #myDataTable').dataTable({          "          bProcessing":          true,          "          bServerSide":          true,          "          sAjaxSource":          '          TableData',          "          aoColumns": [                              {          "          sName":          "          ID",          "          bSearchable":          false,          "          bSortable":          false,          "          bVisible":          false          },                      {          "          sName":          "          COMPANY_NAME"          },                      {          "          sName":          "          ADDRESS"          },                      {          "          sName":          "          TOWN"          }                     ]         }).makeEditable();     });          <          /          script          >          }          <          div                              id          ="          demo"          >          <          h2          >Ajax instance<          /h2          >          <          table                              id          ="          myDataTable"                              class          ="          display"          >          <          thead          >          <          tr          >          <          th          >ID<          /thursday          >          <          th          >Visitor proper noun<          /th          >          <          th          >Address<          /th          >          <          th          >Town<          /th          >          <          /tr          >          <          /thead          >          <          tbody          >          <          /tbody          >          <          /table          >          <          /div          >        

In the DataTables call in JavaScript are added the bServerside and sAjaxSource parameters. Likewise, columns are explicitly defined where you lot tin meet that the ID of the column is added every bit a hidden column. In the AJAX manner, y'all cannot easily put the ID of the record every bit an id attribute of the <TR> tag that surrounds a Company. Therefore, in the AJAX manner, the ID of each record that volition be edited or deleted must be placed in the commencement hidden column of the table. The tabular array body is empty considering it is not generated on the server. Each time data is required, the DataTables plug-in calls the sAjaxSource folio to get the JSON array that will exist dynamically injected into the table body on the client-side. The merely deviation that should be done is in the "Add new row" form. As we have the first column to be the ID of the visitor, we need to put a matching input element with rel="0" in the class for adding a new row. The most convenient thing to practise is to add this element as a hidden input without a name (so information technology volition not be sent to the server), with some dummy value. This element is required then adding a new row in the table would not intermission due to the fact that the number of inputs in the form and columns in the table do not lucifer. The value of this hidden field is irrelevant as the ID will exist taken from the server and gear up in the tabular array as an ID when a row is added. An example of the "Add together new row" form is shown below:

          <          course                              id          ="          formAddNewRow"                              action          ="          #"                              title          ="          Add together new company"          >          <          input                              type          ="          hidden"                              id          ="          id"                              name          ="          id"                              value          ="          -1"                              rel          ="          0"                              /          >          <          label                              for          ="          name"          >Name<          /label          >          <          input                              type          ="          text"                              proper noun          ="          name"                              id          ="          name"                              class          ="          required"                              rel          ="          one"                              /          >          <          br                              /          >          <          label                              for          ="          name"          >Address<          /label          >          <          input                              type          ="          text"                              name          ="          address"                              id          ="          address"                              rel          ="          2"                              /          >          <          br                              /          >          <          label                              for          ="          name"          >Postcode<          /label          >          <          input                              type          ="          text"                              name          ="          postcode"                              id          ="          postcode"          /          >          <          br                              /          >          <          label                              for          ="          name"          >Boondocks<          /label          >          <          input                              blazon          ="          text"                              name          ="          town"                              id          ="          boondocks"                              rel          ="          three"                              /          >          <          br                              /          >          <          label                              for          ="          proper name"          >Country<          /label          >          <          select                              name          ="          country"                              id          ="          country"          >          <          option                              value          ="          1"          >Serbia<          /selection          >          <          option                              value          ="          2"          >France<          /pick          >          <          option                              value          ="          iii"          >Italian republic<          /selection          >          <          /select          >          <          br                              /          >          <          /course          >        

Controller

In my previous article, I explained how you tin can implement a controller to piece of work with DataTables in server-side mode. In short, two major differences are:

  1. Controller activity that is executed when the view page is requested does cipher. No model is associated to the view as data binding is non done on the server-side.
  2. An additional activity that volition be referenced via sAjaxSource must exist implemented where all the processing is washed on the server-side.

Integration of the DataTables plug-in with server-side code is not covered hither, merely you can find how this tin can be implemented in the article Integrating the jQuery DataTables plug-in into an ASP.NET MVC application. In this commodity, yous can observe how to supervene upon client-side pagination, filtering, and ordering functionalities used in this commodity, with server-side actions, in order to improve the performance of DataTables.

Full Customization

In the examples higher up, I have shown a few out of the box functionalities of the DataTable Editable plug-in that can exist used without any modify. Still, similar to the original DataTables plug-in, the DataTables Editable plug-in allows you to configure properties of the plug-in and customize it. In this department, I will explain how this plug-in tin can be customized.

Setting AJAX URLs

The first matter you might want to alter are URLs that will be called to update, delete, or add together information. By default, if the URL of the page where the tabular array is rendered is /Company/Index, URLs for data management operation will be /Company/UpdateData, /Company/AddData, and /Visitor/DeleteData. This is very user-friendly for ASP.Internet MVC applications because these actions can be placed inside the same controller. If y'all accept a unlike controller or prepare of views, e.g., /Employee/Listing or /Director/Details, where the editable data table is placed, you volition only add UpdateData, DeleteData, and AddData into the advisable controllers and each page volition phone call its data management activity. Yet, you are able to completely customize data management URLs and put any URL you desire. The instance below shows how you can configure the DataTables Editable table to use PHP pages instead of ASP.Cyberspace MVC pages. You lot tin can put any value instead of these (other MVC pages, ASPX pages, etc.).

$('          #myDataTable').dataTable().makeEditable({                     sUpdateURL:          "          /Dwelling/UpdateData.php",                     sAddURL:          "          /Home/AddData.php",                     sDeleteURL:          "          /Home/DeleteData.php"          });        

Configuring DOM

You saw that lot of elements such as buttons are auto-generated past the plug-in. The simply thing you need to do is to define an element with class "add_delete_toolbar" that will be the placeholder for Add together and Delete buttons. If you want total command over the content, y'all tin can put these buttons directly in the view page. If DataTables Editable finds that buttons already exists, new ones will non be generated and event handlers will exist attached to the existing ones. The only thing you lot demand to do is to put the expected IDs into the HTML elements yous want to utilise then DataTables Editable tin can find them. The default IDs of the elements are:

  • formAddNewRow - ID of the form that will be shown in the popup dialog when a new row is added
  • btnAddNewRow - push that opens the dialog for calculation a new row
  • btnAddNewRowOk - confirmation button in the Add New Row dialog
  • btnAddNewRowCancel - abolish button in the Add New Row dialog
  • btnDeleteRow - button for deleting the selected row

Note that these elements do non need to exist <push button> HTML elements - you tin can place anything yous want, e.g., <a>, <bridge>, <input>, <img>, etc. The only requirement is that these elements have expected IDs. If you practice non like these IDs, you can change them too. This is suitable if you lot have two different tables you enhanced with the DataTables Editable plug-in on the same page and yous do not want to mix their control buttons. An example configuration of the DataTables Editable plug-in with the definition of IDs of the command buttons is shown below:

$('          #myDataTable').dataTable().makeEditable({                         sAddNewRowFormId:          "          formAddNewCompany",                     sAddNewRowButtonId:          "          btnAddNewCompany",                     sAddNewRowOkButtonId:          "          btnAddNewCompanyOk",                     sAddNewRowCancelButtonId:          "          btnAddNewCompanyCancel",                     sDeleteRowButtonId:          "          btnDeleteCompany",                 });

To use this configuration, you will need to place elements with exactly same IDs and position them into the folio wherever you like. If you don't desire a placeholder for adding Add and Delete buttons to exist a div with class add_delete_toolbar, y'all can change this too. The configuration I frequently utilise to inject the buttons in the table header on the correct side of "Evidence 30 entries per page" is shown in the example below:

$('          #myDataTable').dataTable().makeEditable({          '          sAddDeleteToolbarSelector':          '          .dataTables_length'          });

The DataTables plug-in places "Show Thirty entries per folio" into the div with form "datatable_length". If I put this class as a selector for the toolbar, the DataTables Editable plug-in will inject Add and Delete buttons in that div.

Customizing the Error Letters

If yous don't like the standard browser'due south message box that is shown when an fault occurs, you can change this behaviour. In the DataTables Editable initialization, you lot can pass your custom mistake function. This part should accept two parameter messages that will be shown and the action that caused an error. An instance of using a custom show bulletin role is shown in the instance below:

$('          #myDataTable').dataTable().makeEditable({                     fnShowError:          function          (bulletin, activity) {          switch          (action) {          example          "          update":                                 jAlert(message,          "          Update failed");          break;          case          "          delete":                                 jAlert(bulletin,          "          Delete failed");          intermission;          case          "          add":                                 $("          #lblAddError").html(message);                                 $("          #lblAddError").show();          break;                         }                     }                 });

In this case, when an error occurs when adding a new record, a bulletin is placed in the error characterization with an ID "lblAddError" (the supposition is that this characterization is placed in the grade that will be shown in the dialog and that it is initially subconscious). For update and delete, error letters are used in a custom jAlert plug-in that shows a "fancy" message box instead of the standard one. Y'all tin can use any other plug-in y'all want instead of this i. An case of implementation of custom messages can be establish on this live demo site.

Configure Custom Editors for the Columns

Editing cells using textboxes is default behaviour for the Jeditable but this plug-in enables you to use different editors for each cavalcade. Every bit an case, in some cases, you will want to utilize a TextArea or select list for inline editing instead of a textbox.

If yous laissez passer aoColumns parameter to the datatable'south initialization office, y'all volition exist able to configure the editors for each column in the tabular array. The parameter aoColumns represents an array of objects containing the properties of the inline editor. An instance of the implementation of custom editors can be found in this alive demo site. Configuration of the custom cavalcade editors is shown in the script beneath:

$('          #myDataTable').dataTable().makeEditable({          "          aoColumns": [     {              },          null,     {         indicator:          '          Saving...',         tooltip:          '          Click to select town',         loadtext:          '          loading...',         type:          '          select',         onblur:          '          submit',          data:          "          {'London':'London','Liverpool':'Liverpool','Portsmouth':               'Portsmouth','Edinburgh':'Edinburgh', 'Blackburn':'Blackburn',               'Kent':'Kent','Essex':'Essex','Oxon':'Oxon','Lothian':'Lothian',               'Westward Sussex':'West Sussex','Lanarkshire':'Lanarkshire',               'Birmingham':'Birmingham','East Sussex':'Eastward Sussex','Surrey':'Surrey'}"          } ] });

The first object in the aoColumns array definition is an empty object {}. If you lot pass an empty object as a configuration parameter for some column, the default editor volition exist used. The 2d object in the assortment is a nil value. This value makes the cavalcade read-only, i.e., the editable plug-in will not be applied on the cells in the second column. This is useful if you lot have HTML links in some cells and yous do non desire to let the user to edit them.

The third element is the nearly interesting one. Here is placed a configuration object for the Jeditable editor that volition be practical on the cells in the tertiary column. The editor that volition be used on the cells in the third cavalcade will be a select list (blazon: 'select') with the listing elements defined in the data holding. The inline select list that will be shown when the user click on the cells in the third cavalcade is shown in the following figure:

MVC-CRUD-DataTable/inline-select-list.png

The information belongings contains a set of value:label pairs that will be used to build a listing. A label will exist shown in the list and the value will be used to update the cell content and it will be sent to the server-side. Submitting the selected value happens when the user clicks on any other cell causing the onblur event. The configuration is prepare so that the onblur selected value should exist submitted to the server (onblur:'submit'). If you do not want this behaviour, you tin can remove the onblur:'submit' selection and place the submit:'Ok' option in the configuration. This volition add together a submit button with the characterization 'Ok' to the left of the select list and the value volition be submitted to the server when the user presses this push. You tin can even utilise a server-side page as a information source for the list if you put the loadurl parameter instead of the data parameter. This configuration forces the loadurl parameter to read values for the select list from the URL instead of the local data array.

Other parameters in the cavalcade configuration set the tooltip and text that will be shown while the editor is processing results using the AJAX call. The configuration parameters that can exist used for the individual editor setup can exist found on the Jeditable site, therefore it might be good to have a look at this site first if you are going to configure the individual editors per column.

Jeditable is a very powerful plugin that has a lot of plugins for custom input types so y'all tin can use date/time pickers, masked inputs, AJAX uploads, or even easily create your own editor. You can see the various input types on the Jeditable custom input demo site.

Summary

This article shows you lot how to create a datatable that has integrated add together, edit, and delete functionalities using the jQuery Datatables Editable plug-in. This plug-in enables you lot to focus just on the server-side functionalities that handle data management requests and implement only code that is specific for your application. The complete example tin can be downloaded from above.

The plug-in with documentation is hosted here so yous can take the plug-in or example of usage and include information technology in your projection.

History

  • sixth March, 2011: Initial version

Ajax Datatables Cannot Read Property Length of Undefined

Source: https://www.codeproject.com/articles/165410/asp-net-mvc-editable-datatable-jquery-datatables-a

0 Response to "Ajax Datatables Cannot Read Property Length of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel