Quiero mostrar los datos de employeeTbl a través de la llamada jQuery Ajax. El método de acción carga los datos y muestra la salida de los datos db en una matriz. Por favor, ayúdenme a obtener la Vista adecuada a través del Método jQuery Ajax.

Aquí está mi código de controlador:

public JsonResult getData()
{
    List<employee> empList = new List<employee>();
    empList = db.employees.ToList();
    return Json(empList, JsonRequestBehavior.AllowGet);
}

Y esta es la vista que estoy presentando:

@model IEnumerable<jQueryPoject.Models.employee>
@{
    ViewBag.Title = "Home Page";
}

<!DOCTYPE html>
<html>
<head>

    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">

     //   $(document).ready(function () {
       //     loadData();
        //});

        // Load Data Function
        function loadData() {
            $.ajax({
                url: "/Home/JsonView",
                type: "GET",
                contentType: "json",
                success: function (result) {
                    var html = '';
                    $.each("#tbody", result, function (key, item) {
                        html += '<tr>';
                        html += '<td>' + item.ID + '</td>';
                        html += '<td>' + item.Name + '</td>';
                        html += '<td>' + item.Age + '</td>';
                        html += '<td>' + item.Salary + '</td>';
                        html += '<td>' + item.Contact + '</td>';
                        html += '<td>' + item.Email + '</td>';
                        html += '</tr>';
                    });
                    $('.tbody').html(html);
                },
                error: function (errormessage) {
                    alert(errormessage.responseText);
                }
            });
        }
    </script>
</head>
<body>
    <div class="jumbotron">
        <h1>ASP.NET</h1>
        <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
        <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
    </div>
    <br />
    <br />

    <div class="container">
        <table id="tbl" class="table table-striped">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Age</th>
                    <th>Salary</th>
                    <th>Contact</th>
                    <th>Email</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>

    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
</body>
</html>

Y este es el resultado que estoy obteniendo:

    [{"ID":1,"Name":"Sami","Age":"25","Salary":"28000","Contact":"111","Email":"s.rehman@texitech.com"},
    {"ID":2,"Name":"Muhammad Sami ur Rehman","Age":"25","Salary":"38970","Contact":"111","Email":"s.rehman@texitech.com"},
    {"ID":3,"Name":"Bilawal Bhutto","Age":"28","Salary":"18000","Contact":"0213333333","Email":"b.bhutto@gmail.com"},
    {"ID":4,"Name":"Bilawal Bhutto","Age":"28","Salary":"18000","Contact":"0213333333","Email":"b.bhutto@gmail.com"},
    {"ID":5,"Name":"Bilawal Bhutto","Age":"22","Salary":"20000","Contact":"ghfhj","Email":"b.bhutto@gmail.com"},
    {"ID":6,"Name":"Bilawal Bhutto","Age":"22","Salary":"20000","Contact":"03128646765","Email":"b.bhutto@gmail.com"},
    {"ID":7,"Name":"Tehmina Jawed","Age":"22","Salary":"20000","Contact":"02134598989","Email":"tehmina.jawed@gmail.com"},
    {"ID":8,"Name":"Sameer BAloch","Age":"22","Salary":"200000","Contact":"111","Email":"samirehman621@gmail.com"},
    {"ID":9,"Name":"Ali Zaidi","Age":"22","Salary":"18000","Contact":"02134598989","Email":"ali.zaidi@yahoo.com"},
    {"ID":10,"Name":"Bilawal Bhutto","Age":"22","Salary":"20000","Contact":"0213333333","Email":"b.bhutto@gmail.com"},{"ID":11,"Name":"hmgm","Age":"22","Salary":"38970","Contact":"ghfhj","Email":"samirehman621@gmail.com"},
    {"ID":12,"Name":"Tehmina Jawed","Age":"22","Salary":"20000","Contact":"ghfhj","Email":"samirehman621@gmail.com"},
    {"ID":13,"Name":"Bilawal Bhutto","Age":"22","Salary":"20000","Contact":"ghfhj","Email":"b.bhutto@gmail.com"},{"ID":14,"Name":"hmgm","Age":"222","Salary":"20000","Contact":"111","Email":"samirehman621@gmail.com"},
    {"ID":15,"Name":"Bilawal Bhutto","Age":"222","Salary":"20000","Contact":"ghfhj","Email":"m.shariq@gmail.com"},
    {"ID":16,"Name":"Bilawal Bhutto","Age":"22","Salary":"20000","Contact":"0213333333","Email":"b.bhutto@gmail.com"},
    {"ID":17,"Name":"Bilawal Bhutto","Age":"26","Salary":"20000","Contact":"0213333333","Email":"b.bhutto@gmail.com"},
    {"ID":18,"Name":"Bilawal Bhutto","Age":"22","Salary":"18000","Contact":"ghfhj","Email":"asdas@f.com"},
    {"ID":19,"Name":"Muhammad Shariq","Age":"26","Salary":"38970","Contact":"0213333333","Email":"m.shariq@gmail.com"},
    {"ID":20,"Name":"Bilawal Bhutto","Age":"22","Salary":"20000","Contact":"0213333333","Email":"samirehman621@gmail.com"},
   {"ID":21,"Name":"Bilawal Bhutto","Age":"22","Salary":"20000","Contact":"0213333333","Email":"b.bhutto@gmail.com"},
   {"ID":22,"Name":"Bilawal Bhutto","Age":"22","Salary":"18000","Contact":"ghfhj","Email":"samirehman621@gmail.com"}, 

 {"ID":23,"Name":null,"Age":null,"Salary":null,"Contact":null,"Email":null}, 
 {"ID":24,"Name":"Tehmina Jawed","Age":"222","Salary":"20000","Contact":"111","Email":"m.shariq@gmail.com"},
 {"ID":25,"Name":null,"Age":null,"Salary":null,"Contact":null,"Email":null}]
-1
M Sami Ur Rehman 17 sep. 2018 a las 14:34

3 respuestas

La mejor respuesta

Aquí está la respuesta de mi pregunta, encontré la solución en youtube.

JQuery Script of my View:

<script type="text/javascript">
    $(function () {
        $.get("/Home/getData", {}, function (data) {
            var row;
            $.each(data, function (i, v) {
                row += "<tr><td>" + v.ID + "</td><td>" + v.Name + "</td><td>" + v.Age + "</td><td>" + v.Salary + "</td><td>" + v.Contact + "</td><td>" + v.Email + "</td></tr>";
            });
            $("#dataTable").append(row);
        })
    })
    </script>

Y el código del controlador está aquí:

 public JsonResult getData()
        {
            DataSet ds = db1.GetAllrecord();
            List<employee> empList = new List<employee>();
            foreach(DataRow dr in ds.Tables[0].Rows)
            {
                empList.Add(new employee
                {
                    ID = Convert.ToInt32(dr["ID"]),
                    Name = dr["Name"].ToString(),
                    Age = dr["Age"].ToString(),
                    Salary = dr["Salary"].ToString(),
                    Contact = dr["Contact"].ToString(),
                    Email = dr["Email"].ToString()
                });
            }



            return Json(empList, JsonRequestBehavior.AllowGet);




        }

Y aquí está la función de clase de modelo:

 public DataSet GetAllrecord()

        {

            SqlCommand com = new SqlCommand("Select * from  employee", con);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }
0
M Sami Ur Rehman 25 sep. 2018 a las 05:50

Cambie el selector de clase .tbody a tbody y debería funcionar, donde tbody es un selector de elementos

$(result).each(function (key, item) {
    html += '<tr>';
    html += '<td>' + item.ID + '</td>';
    html += '<td>' + item.Name + '</td>';
    html += '<td>' + item.Age + '</td>';
    html += '<td>' + item.Salary + '</td>';
    html += '<td>' + item.Contact + '</td>';
    html += '<td>' + item.Email + '</td>';
    html += '</tr>';
});

$('tbody').html(html);

Agregue dataType, el tipo que se espera que vuelva del servidor

dataType: "json" y contentType: "application/json"

0
mbharanidharan88 17 sep. 2018 a las 12:00

Oye, intenta lo mismo que yo.

    // Load Data Function
    function loadData() {
        $.ajax({
            url: "/Home/JsonView",
            type: "GET",
            contentType: "json",
            success: function (result) {
                var html = '';
                var count = Object.keys(result).length;
                for(var i = 0; i< count; i++){
                    html += '<tr>';
                    html += '<td>' + result[i].ID + '</td>';
                    html += '<td>' + result[i].Name + '</td>';
                    html += '<td>' + result[i].Age + '</td>';
                    html += '<td>' + result[i].Salary + '</td>';
                    html += '<td>' + result[i].Contact + '</td>';
                    html += '<td>' + result[i].Email + '</td>';
                    html += '</tr>';
                }
                $('.tbody').html(html);
               // you could try append too
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    }

Para hacer un bucle de datos json.

0
Muhammed Sami 17 sep. 2018 a las 12:01