LaVOZs

The World’s Largest Online Community for Developers

'; asp.net mvc - Accessing MVC's model property from Javascript to fill jQuery datatable insted of using json - LavOzs.Com

I am trying to build an ASP.NET MVC application I want to return a model instead of json but I need help to use to model to fill my datatable.

Here is my Javascript:

   @section Scripts{
        <script type="text/javascript" charset="utf8" src="~/Scripts/DataTables/jquery.dataTables.js"></script>
        <script>
            $(document).ready(function () {
                $('#proveedorContactoTable').DataTable({
                    "ajax": {
                        "url": "/fichaProveedor/loadProveedorContactoTable",
                        "type": "GET",
                        "datatype": "json"
                    },
                    "columns": [
                        { "data": "nombre_contacto", "autoWidth": true }, /* index = 0 */
                        { "data": "apellido_contacto", "autoWidth": true }, /* index = 1 */
                        { "data": "carga_contacto", "autoWidth": true }, /* index = 2 */
                        { "data": "telefono_fijo_contacto", "autoWidth": true }, /* index = 3 */
                        { "data": "telefono_movil_contacto", "autoWidth": true }, /* index = 4 */
                        { "data": "correo_contacto", "autoWidth": true }, /* index = 5 */
                        { "data": "principal", "autoWidth": true }, /* index = 6 */
                        {
                            "data": "contacto_id", "width": "50px", "render": function (data) {
                                return '<a class="popup" href="/fichaProveedor/Detalles/' + data + '">Editar</a>';  /* index = 7 */
                            }
                        },
                        {
                            "data": "contacto_id", "width": "50px", "render": function (data) {

                                return '<a class="btn btn-primary" href="/fichaProveedor/Eliminar/' + data + '">Eliminar</a>'; /* index = 8 */
                            }
                        }
                    ],
                    'columnDefs': [{
                        'targets': [7, 8], /* column index */
                        'orderable': false, /* true or false */
                    }]
                });
            });

        </script>
    }

And here is my html table

<div class="dvScroll">
    <table id="myTable">
        <thead>
            <tr>
                <th>Proveedor Id</th>
                <th>Nombre</th>
                <th>Dirección</th>
                <th>Código postal</th>
                <th>Cuidad</th>
                <th>País</th>
                <th>Pagina internet</th>
                <th>Edit</th>
                <th>Delete</th>
            </tr>
        </thead>
    </table>
</div>

I have the following model that contains a list of "contactos" I want to use all its elements to fill the jQuery table. Here is my model and some of the properties contained in the model.

@model erp_colombia.Models.proveedorModel
@foreach (var contacto in Model.contactos)
{
        @contacto.contacto_id
        @contacto.apellido_contacto
}

Here is my controller so far

[HttpPost]
public ActionResult Editar(inventarioModel gestiondeubicacione)
{
    inventarioContext gestiondeubicaciones = new inventarioContext();
    bool status = false;
    if (ModelState.IsValid)
    {
        if (gestiondeubicacione.componente_id > 0)
        {
            //Edit 
            var gestiondeubicacionesFound = gestiondeubicaciones.GetAllInventarios().Where(a => a.componente_id == gestiondeubicacione.ubicacion_id).FirstOrDefault();
            if (gestiondeubicacionesFound != null)
            {
                gestiondeubicacionesFound.armario = gestiondeubicacione.armario;
                gestiondeubicacionesFound.cajon = gestiondeubicacione.cajon;
            }
        }
        else
        {
            //gestiondeubicaciones.addInvenotryLocationToDB(gestiondeubicacione);
            TempData["msgType"] = messageType.success;
            TempData["msg"] = "Nueva ubicación agregada!";
            //Save new one
            //dc.Employees.Add(emp);
        }
        //gestiondeubicaciones.updateInvenotryLocationToDB(gestiondeubicacione);
        TempData["msgType"] = messageType.success;
        TempData["msg"] = "La ubicación ha sido actualizada!";
        //Update
        //dc.SaveChanges();
        status = true;
    }
    return new JsonResult { Data = new { status = status } };
}

How can I use my model inside the Javascript instead of the json? Thank you very much for your help.

  1. JSON Controller
[Route("fichaProveedor")]
public class ReportingController : ControllerBase 
{
       [HttpGet("loadProveedorContactoTable")]
        public async Task<IActionResult> LoadProveedorContactoTable()
        {
           var erp_colombia = //load result here
           return Ok(erp_colombia.Models.proveedorModel);
        }
}
  1. WebAPI client View
<script type="text/javascript" charset="utf8" src="~/Scripts/DataTables/jquery.dataTables.js"></script>
<table id="proveedorContactoTable" class="display" style="width:100%">
</table>
        <script>
            $(document).ready(function () {
                $('#proveedorContactoTable').DataTable({
                    "ajax": {
                        "url": "/fichaProveedor/loadProveedorContactoTable",
                        "type": "GET",
                        "datatype": "json"
                    },
                    "columns": [
                        { "data": "nombre_contacto", "autoWidth": true }, /* index = 0 */
                        { "data": "apellido_contacto", "autoWidth": true }, /* index = 1 */
                        { "data": "carga_contacto", "autoWidth": true }, /* index = 2 */
                        { "data": "telefono_fijo_contacto", "autoWidth": true }, /* index = 3 */
                        { "data": "telefono_movil_contacto", "autoWidth": true }, /* index = 4 */
                        { "data": "correo_contacto", "autoWidth": true }, /* index = 5 */
                        { "data": "principal", "autoWidth": true }, /* index = 6 */
                        {
                            "data": "contacto_id", "width": "50px", "render": function (data) {
                                return '<a class="popup" href="/fichaProveedor/Detalles/' + data + '">Editar</a>';  /* index = 7 */
                            }
                        },
                        {
                            "data": "contacto_id", "width": "50px", "render": function (data) {

                                return '<a class="btn btn-primary" href="/fichaProveedor/Eliminar/' + data + '">Eliminar</a>'; /* index = 8 */
                            }
                        }
                    ],
                    'columnDefs': [{
                        'targets': [7, 8], /* column index */
                        'orderable': false, /* true or false */
                    }]
                });
            });

        </script>
  1. MVC Controller
[Route("fichaProveedor")]
public class ReportingController : ControllerBase 
{
       [HttpGet("loadProveedorContactoTable")]
        public ActionResult LoadProveedorContactoTable()
        {
           var erp_colombia = //load result here
           return erp_colombia.Models.proveedorModel;
        }
}
  1. WebAPI client View
    <script type="text/javascript" charset="utf8" src="~/Scripts/DataTables/jquery.dataTables.js"></script>
@model erp_colombia.Models.proveedorModel
    <table id="proveedorContactoTable" class="display" style="width:100%">
      @foreach (var contacto in Model.contactos)
{
        <tr><td>@contacto.contacto_id</td>
        <td>@contacto.apellido_contacto</td></tr>
}
    </table>
            <script>
                $(document).ready(function () {
                    $('#proveedorContactoTable').DataTable({
                        "columns": [
                            { "data": "nombre_contacto", "autoWidth": true }, /* index = 0 */
                            { "data": "apellido_contacto", "autoWidth": true }, /* index = 1 */
                            { "data": "carga_contacto", "autoWidth": true }, /* index = 2 */
                            { "data": "telefono_fijo_contacto", "autoWidth": true }, /* index = 3 */
                            { "data": "telefono_movil_contacto", "autoWidth": true }, /* index = 4 */
                            { "data": "correo_contacto", "autoWidth": true }, /* index = 5 */
                            { "data": "principal", "autoWidth": true }, /* index = 6 */
                            {
                                "data": "contacto_id", "width": "50px", "render": function (data) {
                                    return '<a class="popup" href="/fichaProveedor/Detalles/' + data + '">Editar</a>';  /* index = 7 */
                                }
                            },
                            {
                                "data": "contacto_id", "width": "50px", "render": function (data) {

                                    return '<a class="btn btn-primary" href="/fichaProveedor/Eliminar/' + data + '">Eliminar</a>'; /* index = 8 */
                                }
                            }
                        ],
                        'columnDefs': [{
                            'targets': [7, 8], /* column index */
                            'orderable': false, /* true or false */
                        }]
                    });
                });

            </script>
Related
jQuery/JavaScript: accessing contents of an iframe
Sorting jqGrid in ASP.NET MVC client view with jQuery and LINQ-to-Entities
JavaScript/jQuery to download file via POST with JSON data
How to parse JSON data with jQuery / JavaScript?
fill jquery datatable with Json array MVC 4
Accessing MVC's model property from Javascript
Accessing a Datatable in JavaScript or JQuery
Filling a Datatable with a JSON from an API