Send a custom parameter from view side to server side

Send a custom parameter from view side to server side

mocotomocoto Posts: 3Questions: 1Answers: 0

Hi guys

I'm starting to use this plugin and I need your help.
I dont know how to send a costume parameter to the server side (C#)

This is my code:

HTML

<table id="datatable" class="table table-striped table-bordered" style="width:100%">
         <thead>
               <tr>
                   <th>Name</th>
               </tr>
         </thead>
</table>

JAVASCRIPT

var table = $('#datatable').DataTable({
                Processing: true,
                serverSide: true,
                ajax: {
                    url: "@Url.Action("CustomServerSideSearchAction", "Entities")",
                    type: 'POST'
                },
                columns: [
                    { "data": "Name" },
                ],
            });

SERVER SIDE C#

#region OBJECTS
public class DataTableAjaxPostModel
{
    public int draw { get; set; }
    public int start { get; set; }
    public int length { get; set; }
    public List<Column> columns { get; set; }
    public Search search { get; set; }
    public List<Order> order { get; set; }
}
public class Column
{
    public string data { get; set; }
    public string name { get; set; }
    public bool searchable { get; set; }
    public bool orderable { get; set; }
    public Search search { get; set; }
}
public class Search
{
    public string value { get; set; }
    public string regex { get; set; }
}
public class Order
{
    public int column { get; set; }
    public string dir { get; set; }
}
public class YourCustomSearchClass
{
    public string Name { get; set; }
}
#endregion
public JsonResult CustomServerSideSearchAction(DataTableAjaxPostModel model)
{
    int filteredResultsCount;
    int totalResultsCount;
    MainDBDataContext db = Models.DataMethods.GetDataContext();

    IQueryable<Entities> allEntities = db.Entities.Where(...);
    totalResultsCount = allEntities.Count();
    filteredResultsCount = allEntities.Count();

    var result = new List<YourCustomSearchClass>();

    foreach (var en in allEntities)
    {
        result.Add(new YourCustomSearchClass
        {
            Name = en.Name
        });
    }

    return Json(new
    {
        // this is what datatables wants sending back
        draw = model.draw,
        recordsTotal = totalResultsCount,
        recordsFiltered = filteredResultsCount,
        data = result
    });
}

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,117Questions: 26Answers: 4,916

    Maybe you can use the data parameter of the AJAX option to send the desired parameter. Here is the AJAX doc:
    http://api.jquery.com/jquery.ajax/

    Kevin

  • allanallan Posts: 63,075Questions: 1Answers: 10,384 Site admin

    See also ajax.data as DataTables also adds the option of being able to specify it as a function which can be useful.

    Allan

  • mocotomocoto Posts: 3Questions: 1Answers: 0

    Guys thank you for your answers, but they weren't helpful.

    I've already tested it on the client side.

    ...
     ajax: {
                        url: "@Url.Action("CustomServerSideSearchAction", "Entities")",
                        type: 'POST',
                        fnServerParams: function (aoData) {
                            aoData.push({ "name": "someKey ", "value": "test" });
                        }
                    },
    ...
    

    and

    ...
     ajax: {
                        url: "@Url.Action("CustomServerSideSearchAction", "Entities")",
                        type: 'POST',
                        data: function (data) {
                            data.someKey = "test";
                        },
                    },
    ...
    

    But I do not know if it is working perfectly because I do not know how to catch the costum parameter on the server side.

    I need your help!

  • kthorngrenkthorngren Posts: 21,117Questions: 26Answers: 4,916

    You can look at the POST request from the client's browser. For example, in Chrome go to Developer Tools and open the network tab. Reload your page then scroll to the bottom of the headers tab and you will see something like this:

    Form Data     view source     view URL encoded
    someKey: test
    

    I'm not sure how to get the form values in C# but from this SO thread it looks like you would use Request.Form["someKey"] to get the value.

    Kevin

  • allanallan Posts: 63,075Questions: 1Answers: 10,384 Site admin
    Answer ✓

    Use your second one - fnServerParams is legacy and won't work there.

    Also, as Kevin notes, it then becomes a C# question since you need to get the data on the server-side. My understand is the same as Kevin's, use Request.Form to get your data. But the exact semantics of it will depend upon if you are using Web API, MVC.NET, or any other framework.

    Allan

  • mocotomocoto Posts: 3Questions: 1Answers: 0

    Thank you guys! ;)

    This situations has been solved!

    Allan, i used the second exemple as you suggested

  • lillo78lillo78 Posts: 1Questions: 0Answers: 0

    I'm stuck 'cause i'm not able to read the params sent by datatable in my params class:
    Param class:

    public class jQueryDataTableParamModel
        {
            
            public int iDraw { get; set; }
    
            public string sSearch { get; set; }
           ............
    }
    

    Controller

     public ActionResult GetUsers(jQueryDataTableParamModel param)
            {
                ...
                if (!string.IsNullOrEmpty(param.sSearch))
                {
                    filtroUsuarios = consulta
                             .Where(c => c.UserUsuario.Contains(param.sSearch)
                                         ||
                              c.UserNombreCompleto.Contains(param.sSearch)
                                         ||
                              c.RolNombre.Contains(param.sSearch)
                                         ||
                              c.EstructuraOperativaNombre.Contains(param.sSearch));
                }
                else
                {
                    filtroUsuarios = consulta;
                }
               ....
    }
    

    Call to DataTable:

    var table = $('#TablaResultados').DataTable({
                    "className": 'details-control',
                    "bServerSide": true,
                    "processing": true,
                    "ajax": {
                        url: "/UsuariosEstructurasRolesJSON/GetUsers"
                    },
                    "columns": [
                        { data: 0, "sClass": "tdIdvisible" },
                        { data: 2, "className": 'details-control'},
                        { data: 3, "className": 'details-control'},
                        { data: 5, "className": 'details-control' },//Estructura Operativa
                        { data: 7, "className": 'details-control' }//Rol
                    ],
                    'columnDefs': [
                        {
                            'targets': 0,
                            'createdCell': function (td, cellData, rowData, row, col) {
                                $(td).attr('id', 'IdResultado');
                            }
                        }
    
                    ]
                });
    

    Any help would be much apprecitaed. Thanks

  • colincolin Posts: 15,237Questions: 1Answers: 2,598

    Hi @lillo78 ,

    This looks like a different to the original post, so it would be worth raising a new thread. That said, you're not sending any custom params for the server to retrieve - the URL is static and there's no additional ones being send in ajax.data,

    Cheers,

    Colin

This discussion has been closed.