繁体   English   中英

ajax返回的数据未与jquery datatable插件绑定

[英]ajax returned data not binding with jquery datatable plugin

我有一个jQuery数据表UI,我想将其与使用ajax调用返回的数据绑定在一起。 我要显示的视图使用局部视图。 在我的控制器上,我返回json类型。 我可以从ajax调用中获取数据,但是IE会下载它,并将数据与jquery datatable UI绑定在一起。

我试图在主视图和部分视图上都添加jquery脚本,但是没有一个在工作。

这是我在控制器上的代码:

 [HttpPost]
        public ActionResult Index(LShViewModel model, string Command)
        {
            if (Command == "Search")
            {
                //model.CountryIdSelected = model.CountryID;
                //model.CountryIdSelected = null;
                var results = helper.SearchUsers(model.UserName, model.EmailAddress, model.FirstName, model.LastName,  model.CountryID);
                if (model.SearchRecords == null)
                {
                    model.SearchRecords = new List<SearchUserResult>();
                }

                foreach (var result in results)
                {
                    model.SearchRecords.Add(result);
                }
                //model.SearchRecords = results;

            }
            model.States = new SelectList(helper.ListStates(model.CountryID), "ID", "Name");
            model.Countries = new SelectList(helper.ListCountries(), "ID", "Name");
            model.CountryIdSelected = model.CountryID;

           // jsonResult.maxJsonLength = int.MaxValue;
            return Json(model);
        }

这是我的索引页面上的股票:

<script>
    $('#search').click(function () {
        $('#searchResults').dataTable({
            "ajax": {
                "url": "/Learner/Index",
                "dataSrc": "",
                "dataType": "json",
                "success": function (data) {
                    $('#searchResults').dataTable({

                        data: data,
                        columns: [

                            { 'data': 'UserName' },
                            { 'data': 'Email' },
                            { 'data': 'FirstName' },
                            { 'data': 'MiddleName' },
                             { 'data': 'LastName' },
                            { 'data': 'Address' },
                            { 'data': 'City' },
                            { 'data': 'StateID' },
                              { 'data': 'PostalCode' },
                            { 'data': 'Phone' },
                             { 'data': '' },

                        ]
                    })
                }
            }
        });

        var table = $('#searchResults').dataTable();
        table.fnClearTable();
        table.fnDraw();
        $.ajax({

            url: '/Learner/Index',
            method: 'post',
            dataType: 'json',
            dataSrc: "",
            success: function (data) {
                $('#searchResults1').dataTable({

                    data: data,
                    columns: [

                        { 'data': 'UserName' },
                        { 'data': 'Email' },
                        { 'data': 'FirstName' },
                        { 'data': 'MiddleName' },
                         { 'data': 'LastName' },
                        { 'data': 'Address' },
                        { 'data': 'City' },
                        { 'data': 'StateID' },
                          { 'data': 'PostalCode' },
                        { 'data': 'Phone' },
                         { 'data': '' },

                    ]

                });
            }

        });

    })
</script>

这是我的部分观点:

    <div class="col-md-12">
        <h4>Search Results</h4>
    </div>
    <div class="col-md-12">
        <table id="searchResults" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                @*<th> Select</th>*@
                <th>Username</th>
                <th>Email</th>
                <th>First Name</th>
                <th>MI</th>
                <th>Last Name</th>
                <th>Address</th>
                <th>City</th>
                <th>State</th>
                <th>Zip</th>
                <th>Phone</th>
                <th></th>
                @*<th>CE Type</th>*@
            </tr>
        </thead>
        <tbody>
            @{
                for (var i=0; i < Model.SearchRecords.Count; i++)
                {
                    <tr>
                        <td>
                            @*@Html.CheckBox("Select")*@
                            @Model.SearchRecords[i].UserName
                            @Html.HiddenFor(modelItem => Model.SearchRecords[i].CountryID)
                            @Html.HiddenFor(modelItem => Model.SearchRecords[i].CountryCode)
                            @Html.HiddenFor(modelItem => Model.SearchRecords[i].PersonID)
                            @Html.HiddenFor(modelItem => Model.SearchRecords[i].Email)
                            @Html.HiddenFor(modelItem => Model.SearchRecords[i].FirstName)
                            @Html.HiddenFor(modelItem => Model.SearchRecords[i].MiddleName)
                            @Html.HiddenFor(modelItem => Model.SearchRecords[i].LastName)
                            @Html.HiddenFor(modelItem => Model.SearchRecords[i].Address)
                            @Html.HiddenFor(modelItem => Model.SearchRecords[i].City)
                            @Html.HiddenFor(modelItem => Model.SearchRecords[i].UserName)
                            @Html.HiddenFor(modelItem => Model.SearchRecords[i].PostalCode)
                            @Html.HiddenFor(modelItem => Model.SearchRecords[i].Phone) 
                            @*@Html.HiddenFor(modelItem => Model.SearchRecords[i].ACPEID)
                            @Html.HiddenFor(modelItem => Model.SearchRecords[i].AAVSBID)*@
                            @*@Html.HiddenFor(modelItem => Model.SearchRecords[i].CH)*@




                            @*@Html.HiddenFor(modelItem => Model.SearchRecords[i].PhysicianTypeID)*@
                        </td>
                        <td>@Model.SearchRecords[i].Email</td>
                        <td>@Model.SearchRecords[i].FirstName</td>
                        <td>@Model.SearchRecords[i].MiddleName</td>
                        <td>@Model.SearchRecords[i].LastName</td>
                        <td>@Model.SearchRecords[i].Address</td>
                        <td>@Model.SearchRecords[i].City</td>
                        <td>@Model.SearchRecords[i].StateCode</td>
                        <td>@Model.SearchRecords[i].PostalCode</td>

                        @if (Model.SearchRecords[i].Phone != "INVALID")
                        {
                             <td>@Model.SearchRecords[i].Phone</td>
                        }

                         @if (Model.SearchRecords[i].Phone == "INVALID")
                        {
                             <td> <text></text></td>
                        }

                        <td>
                            <div class="dropdown">
                                <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
                                    Manage

                                </button>
                                <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
                                    <li role="presentation"><a role="menuitem" tabindex="-1" href="@Url.Action("ViewProfile1", "Learner", new { personid=Model.SearchRecords[i].PersonID})">View Profile</a></li>                                        

                                </ul>
                            </div>
                        </td>
                    </tr>
                }
            }
        </tbody>
        </table>
    </div>

我已经创建了一个局部视图,当单击主页中的按钮时,它将打开。 我已经在局部视图中添加了数据表。 请检查以下代码。

Index.cshtml

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
    <script src="http://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="http://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

    <script type="text/javascript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet">
    <script type="text/javascript">
        $(function () {
            $('#showDatatable').click(function () {
                $("#partialViewDiv").html('');
                var request = $.ajax({
                    url: "Learner/GetPartialView",
                    method: "POST",
                    dataType: "html"
                });
                request.done(function (msg) {
                    $("#partialViewDiv").html(msg);
                    $("#partialViewDiv").dialog({
                        height: 400,
                        resizable: false,
                        width: 800,
                        title: "Search"
                    });
                    createDatatableGrid();
                });
            });

            function createDatatableGrid() {
                $('#searchResults').dataTable({
                    bFilter: false,
                    bLengthChange: false,
                    "sDom": 'lfrtip',
                    pagingType: 'full',
                    "oLanguage": {
                        "oPaginate": {
                            "sFirst": "<b><<</b>",
                            "sLast": "<b>>></b>",
                            "sNext": "<b>></b>",
                            "sPrevious": "<b><</b>"
                        }
                    }
                });
            }
            createDatatableGrid();
        });
    </script>

</head>
<body>
    <button id="showDatatable" type="button">Show Datatable</button>
    <div id="partialViewDiv"></div>
</body>
</html>

学习者控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class LearnerController : Controller
    {
        //
        // GET: /Learner/

        public ActionResult GetPartialView()
        {
            return PartialView("Partial1");
        }

        public JsonResult Index()
        {
            List<User> user = new List<User>();
            user.Add(new User()
            {
                Username = "User1",
                Email ="user1@u.com",
                FirstName = "FirstName1",
                MI = "MI1",
                LastName = "LastName1",
                Address = "Address1",
                City = "City1",
                State = "State1",
                Zip = "Zip1",
                Phone = "Phone1",
            });

            return Json(user, JsonRequestBehavior.AllowGet);
        }

    }
}

Partial1.cshtml

    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "Learner/Index",
                dataType: "json",
                success: function (values) {
                    $('#searchResults').dataTable().fnClearTable();
                    for (var i = 0; i < values.length; i++) {
                        var user = values[0];
                        $('#searchResults').dataTable().fnAddData([
                              user.Username,
                              user.Email,
                              user.FirstName,
                              user.MI,
                              user.LastName,
                              user.Address,
                              user.City,
                              user.State,
                              user.Zip,
                              user.Phone,
                              ""
                        ]);
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });
        });
    </script>
    <div class="col-md-12">
        <h4>Search Results</h4>
    </div>
    <div class="col-md-12">
        <table id="searchResults" class="display" cellspacing="0" width="100%">
            <thead>
                <tr>
                    @*<th> Select</th>*@
                    <th>Username</th>
                    <th>Email</th>
                    <th>First Name</th>
                    <th>MI</th>
                    <th>Last Name</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>State</th>
                    <th>Zip</th>
                    <th>Phone</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>

**User Model**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication1.Models
{
    public class User
    {
        public string Username { get; set; }
        public string Email { get; set; }
        public string FirstName { get; set; }
        public string MI { get; set; }
        public string LastName { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
        public string Phone { get; set; }
        public string Address { get; set; }
    }
}

我已经在MVC4应用程序中创建了此示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM