1

我有一个简单的 MVC 应用程序,它从数据库表中获取数据并将其显示在 html 表中。当我尝试使用服务器端处理时,数据被返回,但它显示在浏览器中而不是我的表格中。

这是脚本:

<script>
            $(document).ready(function () {
                $('#patients').dataTable({
                    "bServerSide":true,
                    "bProcessing":true,
                    "sAjaxSource": '@Url.Action("Index","Patient")',
                    "bJQueryUI": true,
                    "sPaginationType": "full_numbers"
                });
            });
</script>

这是html表:

<table width="100%" id="patients">

    <thead>
        <tr>
            <th>First Name</th>
            <th>Last Name</th>

        </tr>
    </thead>
    <tbody>
    </tbody>

</table>

这是我的控制器操作方法:

  public ActionResult Index()
        {
            List<Patient> patients = new List<Patient>();
            using (SqlConnection conn = new SqlConnection("Server=server;Database=db;Trusted_Connection=True"))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT FirstName,LastName FROM Patient",conn))
                {
                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        patients.Add(new Patient { FirstName = reader["FirstName"].ToString(), LastName = reader["LastName"].ToString() });
                    }
                }

            }
            return Json(new
            {
                aaData = patients.Select(x=> new[] {x.FirstName,x.LastName})
            },JsonRequestBehavior.AllowGet);
        }

    }

这是浏览器中显示的 JSON:

{"aaData":[["Tom","Jones"],["Jerry","Jones"],["Jack","Roberts"],["Harry","Truman"],["Bill","Clinton"],["Barrack","Obama"],["George","Bush"],["Ed","Lee"],["Michael","Jordan"],["James","Caan"],["Rick","Reilly"],["Johhny","B.Goode"]]}


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title - My ASP.NET MVC Application</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/css")

        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <header>
            <div class="content-wrapper">
                <div class="float-left">
                    <p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p>
                </div>
                <div class="float-right">
                    <section id="login">
                        @Html.Partial("_LoginPartial")
                    </section>
                    <nav>
                        <ul id="menu">
                            <li>@Html.ActionLink("Home", "Index", "Home")</li>
                            <li>@Html.ActionLink("Patients","Index","Patient")</li>
                            <li>@Html.ActionLink("About", "About", "Home")</li>
                            <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                        </ul>
                    </nav>
                </div>
            </div>
        </header>
        <div id="body">
            @RenderSection("featured", required: false)
            <section class="content-wrapper main-content clear-fix">
                @RenderBody()
            </section>
        </div>
        <footer>
            <div class="content-wrapper">
                <div class="float-left">
                    <p>&copy; @DateTime.Now.Year - My ASP.NET MVC Application</p>
                </div>
            </div>
        </footer>


        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/table")
        @RenderSection("scripts", required: false)
    </body>
</html>
4

2 回答 2

0

您在这里有一些选择:

如果您在加载页面时有数据表的数据,您可能应该只使用模型来携带数据并将其输入到表中。

如果您需要异步加载数据,您需要在控制器上创建不同的操作 - 一个用于加载页面(在本例中为 Index 操作),第二个用于获取数据表的数据。您看到的是尝试使用单个操作来完成这两个操作的结果。

获取数据的操作应如下所示:

public JsonResult PatientsData()
{
   List<Patient> patients = new List<Patient>() {
      new ListItem() { FirstName= "1", LastName = "VA" }
   };

        return Json(new
        {
            aaData = patients.Select(x=> new[] {x.FirstName,x.LastName})
        },JsonRequestBehavior.AllowGet);
}

然后你可以配置你的数据表,如:

$(document).ready(function() {
    $('#example').dataTable( {
        "bProcessing": true,
        "sAjaxSource": '~/Controller/PatientsData'
    } );
} );
于 2013-05-02T12:58:50.553 回答
-1

嗨,您需要从 JSON 结果创建 HTML 表:

function CreateDynamicTable(objArray) {
//var array = JSON.parse(objArray);
var array = objArray;
var str = '<table class="display" cellpadding="0" cellspacing="0" border="0" id="example">';
str += '<thead><tr>';
for (var index in array[0]) {
    str += '<th scope="col">' + index + '</th>';
}
str += '</tr></thead>';
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
    str += (i % 2 == 0) ? '<tr class="gradeA">' : '<tr class="gradeA">';
    for (var index in array[i]) {
            str += '<td>' + array[i][index] + '</td>';
    }
    str += '</tr>';
}
str += '</tbody>'
str += '<tfoot><tr>';
for (var index in array[0]) {
    str += '<th scope="col">' + index + '</th>';
}
str += '</tr></tfoot>';
str += '</table>';
return str;

}

创建数据表的脚本

$.ajax({
                type: 'POST',
                url: '/Index/Patient',
                contentType: 'application/json; charset=UTF-8',
                dataType: 'json',
                success: function (data) {
                    if (data != null) {
                        var objlist = JSON.parse(data);
                        //if no Data
                        if (objlist.toString() != '') {
                            var str = CreateDynamicTable(objlist );
                            //Create HTML Table in  DIV
                            $("#bind").html(str);
                            //Create datatable
                            $('#example').dataTable({
                                "sPaginationType": "full_numbers"                                    
                            });
                        }
                        else {
                            //if no Data
                        }
                    }
                }

            });

和你的 HTML :

<div id="bind">
<table width="100%" id="patients">
<thead>
    <tr>
        <th>First Name</th>
        <th>Last Name</th>

    </tr>
</thead>
<tbody>
</tbody>

于 2013-05-01T10:40:00.813 回答