如何使用“ onclick”分隔输出并将数据格式化为每页20个?

时间:2018-06-21 16:02:02

标签: javascript html ajax jqgrid

在文本框中输入内容后,如何格式化输出使其看起来像这样?

enter image description here

到目前为止,我只能使它起作用:

当前我可以按Enter键:

enter image description here

它返回文本框中的每个“标题”:

enter image description here

最终,我将更新代码以返回不仅仅是“标题”的内容,但现在它的工作方式如下:

Javascript:

function getUrl() {

$("#getUrlResult").val("");
$.ajax({
    contentType: 'application/json',
    type: "GET",
    url: "api/codes",
    success: function (data, textStatus, jqXHR) {
        console.log(data);
        data.items.forEach(function (item) {
            $("#getUrlResult").val($("#getUrlResult").val() + item.title);
        });
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert('Nothing Found');
        console.log(errorThrown);
    }
});

}

HTML:

<body>
<h2>Get Data</h2>

<button onclick="getUrl()">Enter</button>

<input type="text" id="getUrlResult"/>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>
<script src="javascripts/search.js"></script>
</body>

控制器:

[HttpGet]
public async Task<IActionResult> Get([FromQuery] FilterShortUrlDto filter, string id)
{
    var su = await _repo.GetByFilter(filter); //search

    if (su == null)
        return NotFound();

    return Ok(su);
}

存储库:

public async Task<PagedList<ShortUrl>> GetByFilter(FilterShortUrlDto filter)
{
    var fb = new FilterDefinitionBuilder<ShortUrl>();

    var fdefs = new List<FilterDefinition<ShortUrl>>();

    if (!string.IsNullOrWhiteSpace(filter.Search))
    {
        fdefs.Add(fb.Text(filter.Search));
    }

    if (!string.IsNullOrWhiteSpace(filter.Title))
    {
        fdefs.Add(fb.Eq(x=>x.Title, filter.Title));
    }

    int pageSize = 20, page = 1;
    int? skipCount = null;

    if (filter.PageSize == null)
    {
        pageSize = 20;
    }
    else
    {
        pageSize = filter.PageSize.Value;
    }

    if (filter.Page != null)
    {
        page = filter.Page.Value;

        if (filter.Page > 1)
        {
            skipCount = page * pageSize;
        }
    }

    var filt = fdefs.Count == 0
        ? fb.Empty
        : (fdefs.Count == 1 ? fdefs[0] : fb.Or(fdefs)); 


    var results = await _db.Urls
        .Find(filt)
        .Skip(skipCount)
        .Limit(pageSize + 1)
        .ToListAsync();

    return new PagedList<ShortUrl>(results, page, pageSize);
}

如您所见,我将其设置为每页仅显示20个项目,并且我确信这是可行的:

enter image description here

我的最终目标是通过基于文本框中输入的内容来限制/组织数据并以可以按页面查看的顺序/格式输出数据,从而简化浏览数据库的过程。

更新

这是我的页面在运行时的样子: enter image description here

jqGrid:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="css/styles.css">
    <title>Database</title>
    <link rel="stylesheet" crossorigin="anonymous"
          href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"
          integrity="sha256-Md8eaeo67OiouuXAi8t/Xpd8t2+IaJezATVTWbZqSOw=">
    <link rel="stylesheet" crossorigin="anonymous"
          href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
          integrity="sha256-eZrrJcwDc/3uDhsdt61sL2oOBY362qM3lon1gyExkL0=">
    <link rel="stylesheet" crossorigin="anonymous"
          href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.4/css/ui.jqgrid.min.css"
          integrity="sha256-gY7w+ZzYjTPCx5Gx1YexizMJigg1YYwcQ3fAnWgAUTE=">
    <script crossorigin="anonymous" src="https://code.jquery.com/jquery-3.3.1.min.js"
            integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="></script>
    <!-- the next line need be uncommented if you need to use bootstrap.min.js -->
    <!--<script crossorigin="anonymous" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
            integrity="sha256-98vAGjEDGN79TjHkYWVD4s87rvWkdWLHPs5MC3FvFX4="></script>
    <script crossorigin="anonymous" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"
            integrity="sha256-xaF9RpdtRxzwYMWg4ldJoyPWqyDPCRD0Cv7YEEe6Ie8="></script>-->          
    <script>
        $.jgrid = $.jgrid || {};
        $.jgrid.no_legacy_api = true;
    </script>
    <script crossorigin="anonymous"
            src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.4/jquery.jqgrid.min.js"
            integrity="sha256-GN28v8v0UEhIeH35OHeGh9LoP5liiKMRbiIFVQ5flTo="></script>
    <script>
        //<![CDATA[
        $(function () {
            "use strict";
            $("#grid1b").jqGrid({
                url: '/api/codes',
                dataType: 'JSON',
                data: { url: $('#grid1b').val() },
                type: 'GET',
                success: function (data, textStatus, jqXHR) {
                    console.log(data);
                    data.items.forEach(function (item) {
                        $("#grid1b").val($("#grid1b").val() + item.title);
                    });
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert('Nothing Found');
                    console.log(errorThrown);
                },    
                colModel: [
                    { name: "title", label: "Title", width: 100 },
                    { name: "id", label: "Id", width: 150, template: "number" },
                    { name: "code", label: "Code", width: 150, template: "number" },    
                    { name: "originalUrl", label: "Original Url", width: 200, firstsortorder: "desc" },
                    { name: "invdate", label: "Date", width: 75, align: "center", sorttype: "date",
                      formatter: "date", formatoptions: { newformat: "d-M-Y" }
                    },
                ],    
                guiStyle: "bootstrap4",
                iconSet: "fontAwesome",
                idPrefix: "gb1_",
                rownumbers: true,
                sortname: "invdate",
                sortorder: "desc",
                caption: "Search The Database",
                headertitles: true,
                toppager: true,
                pager: true,
                rowNum: 20,
                viewrecords: true,
            }).jqGrid("filterToolbar");
        });
    </script>    
</head>
<body>
<div align="center">
<table id="grid1b"></table>
</div>
    <script src="javascripts/search.js"></script>
</body>
</html>

更新: 由于多次尝试失败,我在最后一次更新中对代码进行了几次更改,以使数据输出到jqGrid。

以下是我最好的朋友DNKROZ建议的Demo

enter image description here

我收到几个错误:

enter image description here

通过更改此方法,我设法弄清了这一点:

<head>
    <!-- The jQuery library is a prerequisite for all jqSuite products -->
    <script type="text/ecmascript" src="../../../js/jquery.min.js"></script> 
    <!-- We support more than 40 localizations -->
    <script type="text/ecmascript" src="../../../js/trirand/i18n/grid.locale-en.js"></script>
    <!-- This is the Javascript file of jqGrid -->   
    <script type="text/ecmascript" src="../../../js/trirand/jquery.jqGrid.min.js"></script>
    <!-- This is the localization file of the grid controlling messages, labels, etc.
    <!-- A link to a jQuery UI ThemeRoller theme, more than 22 built-in and many more custom -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> 
    <!-- The link to the CSS that the grid needs -->
    <link rel="stylesheet" type="text/css" media="screen" href="../../../css/trirand/ui.jqgrid-bootstrap.css" />
    <script>
        $.jgrid.defaults.width = 780;
        $.jgrid.defaults.styleUI = 'Bootstrap';
    </script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <meta charset="utf-8" />
    <title>jqGrid Loading Data - JSON Live</title>
</head>

进入最后一次更新的我自己的更新版本,如下所示:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/cupertino/jquery-ui.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.5/css/ui.jqgrid.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.5/js/jquery.jqgrid.min.js"></script>
    <script>
        $.jgrid = $.jgrid || {};
        $.jgrid.no_legacy_api = true;
    </script>
    <script crossorigin="anonymous"
            src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.4/jquery.jqgrid.min.js"
            integrity="sha256-GN28v8v0UEhIeH35OHeGh9LoP5liiKMRbiIFVQ5flTo="></script>
</head>
<body>
    <div style="margin-left:20px">
        <table id="jqGrid"></table>
        <div id="jqGridPager"></div>
    </div>
    <script type="text/javascript">

        $(document).ready(function () {
            $("#jqGrid").jqGrid({
                colModel: [
                    {
                        label: 'Id',
                        name: 'id',
                        width: 150
                    },
                    {
                        label: 'Title',
                        name: 'title',
                        width: 100
                    },
                    {
                        label: 'Code',
                        name: 'code',
                        width: 150
                    },
                    {
                        label: 'Original Url',
                        name: 'originalUrl',
                        width: 200
                    }
                ],

                viewrecords: true,
                width: 780,
                height: 200,
                rowNum: 20,
                datatype: 'JSON',
                pager: true,
                caption: "I really hope this works..."
            });

            fetchGridData();

            function fetchGridData() {

                var gridArrayData = [];
                // show loading message
                $("#jqGrid")[0].grid.beginReq();
                $.ajax({
                    url: 'api/codes',
                    type: 'GET',
                    //data: JSON.stringify(result),
                    success: function (result) {
                        for (var i = 0; i < result.items.length; i++) {
                            var item = result.items[i];
                            gridArrayData.push({
                                id: item.id,
                                title: item.title,
                                code: item.code,
                                originalUrl: item.originalUrl,
                            });
                        }
                        // set the new data
                        $("#jqGrid").jqGrid('setGridParam', { data: gridArrayData });
                        // hide the show message
                        $("#jqGrid")[0].grid.endReq();
                        // refresh the grid
                        $("#jqGrid").trigger('reloadGrid');
                    }
                });
            }
        });

    </script>
</body>
</html>

警告消失,我的输出现在看起来像这样:

enter image description here

我可能是错的,但我确实相信我的控制器操作正在返回JSON数据,这是我对原因的理解:

当使用Postman测试我的代码时,我“获取”了JSON:

enter image description here

即使我的get函数没有“返回Json(su);”,像这样:

enter image description here

另外,在使用Robo 3T浏览数据库集合时,我注意到右键单击时有一个“ Copy Json”选项:

enter image description here

如果我错了,请纠正我,因为我还是MongoDb / Asp.net Core的新手,但我确实相信它正在实现这一目标,但我不确定jqGrid。

更新

我不得不从here添加一些文件。

enter image description here

还需要这个:

enter image description here

还必须添加“ hiddengrid:true”并调用“ fetchGridData();”在函数之后(由于某种原因)如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">

    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/cupertino/jquery-ui.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.5/css/ui.jqgrid.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.5/js/jquery.jqgrid.min.js"></script>
    <script>
        $.jgrid = $.jgrid || {};
        $.jgrid.no_legacy_api = true;
    </script>
    <script crossorigin="anonymous"
            src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.4/jquery.jqgrid.min.js"
            integrity="sha256-GN28v8v0UEhIeH35OHeGh9LoP5liiKMRbiIFVQ5flTo="></script>

    <link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />

    <link rel="stylesheet" type="text/css" media="screen" href="css/styles3.css" />
    <script src="javascripts/jquery-1.11.0.min.js" type="text/javascript"></script>
    <script src="javascripts/grid.locale-en.js" type="text/javascript"></script>
    <script src="javascripts/jquery.jqGrid.min.js" type="text/javascript"></script>
</head>
<body>
    <div class="center" id="overGrid">
        <table id="jqGrid"></table>
        <div id="jqGridPager"></div>
    </div>
    <script type="text/javascript">

        $(document).ready(function () {
            $("#jqGrid").jqGrid({
                url: 'api/codes',
                editurl: 'api/codes',
                colModel: [
                    {
                        label: "Edit Actions",
                        name: "actions",
                        width: 75,
                        formatter: "actions",
                        formatoptions: {
                            keys: true,
                            editOptions: {},
                            addOptions: {},
                            delOptions: {}
                        }
                    },
                    {
                        label: 'Id',
                        name: 'id',
                        width: 150,
                        editable: true
                    },
                    {
                        label: 'Title',
                        name: 'title',
                        width: 100,
                        editable: true
                    },
                    {
                        label: 'Code',
                        name: 'code',
                        width: 100,
                        editable: true
                    },
                    {
                        label: 'Original Url',
                        name: 'originalUrl',
                        width: 200,
                        editable: true
                    }
                ],
                align: 'center',
                viewrecords: true,
                rowList: [10, 20, 30],
                width: 925,
                height: 445,
                rowNum: 20,
                loadonce: true,
                hiddengrid: true,
                toppager: '#jqGridPager',
                pager: '#jqGridPager',
                caption: "Database"

            }); jQuery("#jqGrid")
                .navGrid('#pager', { edit: false, add: false, del: false, search: false })
                .navButtonAdd('#pager', {
                    caption: "Add",
                    buttonicon: "ui-icon-add",
                    onClickButton: function () {
                        alert("Adding Row");
                    },
                    position: "last"
                })
                .navButtonAdd('#pager', {
                    caption: "Del",
                    buttonicon: "ui-icon-del",
                    onClickButton: function () {
                        alert("Deleting Row");
                    },
                    position: "last"
                });

            function fetchGridData() {    
                var gridArrayData = [];
                // show loading message
                $("#jqGrid")[0].grid.beginReq();
                $.ajax({
                    url: 'api/codes',
                    mtype: 'POST',
                    datatype: 'JSON',
                    success: function (result) {
                        for (var i = 0; i < result.items.length; i++) {
                            var item = result.items[i];
                            gridArrayData.push({
                                id: item.id,
                                title: item.title,
                                code: item.code,
                                originalUrl: item.originalUrl,
                            });
                        }
                        // set the new data
                        $("#jqGrid").jqGrid('setGridParam', { data: gridArrayData });
                        // hide the show message
                        $("#jqGrid")[0].grid.endReq();
                        // refresh the grid
                        $("#jqGrid").trigger('reloadGrid');    
                    }
                });
            }    
            fetchGridData();    
        });     
    </script>    
</body>
</html>

现在输出看起来像这样:

enter image description here

1 个答案:

答案 0 :(得分:1)

由于您没有使用剃刀,因此建议您看一下一些能够生成网格的JavaScript插件。

我目前使用一种名为jqGrid的方法,可以很容易地对其进行自定义,并且很容易进行分页。基本上,它的工作原理是从控制器操作中接收JSON结果,并从附加到其的HTML表格元素生成网格。

这里是documentation

的链接

这里是demo