Using Jquery Datatables with ASP.NET MVC 5

Asked

Viewed 3,595 times

3

I have doubts how to use Datatables with MVC 5 and with Submit button returning a Json as per the site: Datatables

$(document).ready(function() {
$('#example').dataTable( {
    "processing": true,
    "serverSide": true,
    "ajax": {
        "url": "scripts/post.php",
        "type": "POST"
    },
    "columns": [
        { "data": "first_name" },
        { "data": "last_name" },
        { "data": "position" },
        { "data": "office" },
        { "data": "start_date" },
        { "data": "salary" }
    ]
} );} );
  1. Use MVC and not php
  2. How should I place the MVC Actionresult call and return a JSON as the component waits.
  3. I wanted to put fields to filter example Address Name and descend to the controller that two fields and make a call to database returning result that do not know how to convert to Json that component expects:

    {
      "draw": 1,
      "recordsTotal": 57,
      "recordsFiltered": 57,
      "data": [
        {
          "first_name": "Airi",
          "last_name": "Satou",
          "position": "Accountant",
          "office": "Tokyo",
          "start_date": "28th Nov 08",
          "salary": "$162,700"
        },
        {
          "first_name": "Cedric",
          "last_name": "Kelly",
          "position": "Senior Javascript Developer",
          "office": "Edinburgh",
          "start_date": "29th Mar 12",
          "salary": "$433,060"
        }
      ]
    }
    
  • Please create a title that briefly describes your problem. The tags should not be used as a title.

  • http://www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part

1 answer

4


It doesn’t change the way it is done in PHP much. When describing Ajax:

"ajax": {
    "url": "scripts/post.php",
    "type": "POST"
},

Make the View write the JS script as follows:

"ajax": {
    "url": @Url.Action("MinhaAction", "MeuController"),
    "type": "POST"
},

@Url.Action accepts various ways to be called. Once done, declare an Action in your Controller as follows:

[HttpPost]
public JsonResult MinhaAction(FormCollection formCollection) 
{
    // Leia os dados de formCollection aqui (é um dicionário).
    // Retorne um JSON para seu AJAX usando JSON.NET.

    return Json(meusObjetos, JsonRequestBehavior.AllowGet);
}

meusObjetos can user an object or a collection of them. JSON.NET knows how to serialize objects correctly in JSON.

To install JSON.NET, use Nuget:

https://www.nuget.org/packages/Newtonsoft.Json/ }

  • Thanks I will try, but if you have an example code of how to pass filter to be but next to the real.

  • 1

    First evolve with the example code, then open another more specific question. I think it’s a lot for a single answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.