How would I format the output to look something like this after entering something into a text box?
I have only gotten this to work so far:
Currently I can hit enter:
And it returns every single "Title" in the text box:
Eventually I will update my code to return more than just the "Title" but for now it works like this:
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>
Controller:
[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);
}
Repository:
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);
}
As you can see I have it set up to only display 20 items per page and I am certain this is working:
My end goal is to make it easier to browse the database by limiting/organizing the data based on what is entered in that text box and outputting the data in an order/format that can be viewed by page accordingly.
Update
This is what my page looks like when I run:
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>
Update: I have made several changes to the code from my last update, as a result of multiple failed attempts, at getting the data to output to the jqGrid.
Following the Demo suggested by my best friend DNKROZ:
I receive a couple errors:
I managed to figure out that by changing this:
<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>
Into to my own updated version of the last update which looks like this:
<!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>
The warning goes away and my output now looks like this:
I could be wrong but I do believe my controller action is returning JSON data and here is my understanding of why:
When using Postman to test my code I 'get' JSON back:
Even though my get function doesn't "return Json(su);" like so:
Also while looking through the database collection using Robo 3T I noticed when right clicking there is an option to "Copy Json":
Correct me if I am wrong as I am still new to MongoDb / Asp.net Core but I do believe that it is working on that end I just am not sure about the jqGrid.
Update:
I had to add a few files from here.
Also need this:
Also had to add "hiddengrid: true" AND call "fetchGridData();" after the function (for some reason) like so:
<!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>
Now the output looks like this:
Since you're not using razor, I'd recommend taking a look at some JavaScript plugins which are able to generate grids.
I currently use one called jqGrid which can be customized pretty easily and is quite simple to get working with paging. It basically works by receiving a JSON result from your controller action and generates a grid from the HTML table element that you attached it to.
Here's a link to the documentation
Here's a demo