How to implement Datatable in boostrap table - asp.net

I want create Jquery Datatable with Paging,Sorting,Searching in my ASP.NET web Api project as this youtube clip
in my bootstrap table as shown below. I don not recieve any Error but not showing me pagin field, serach field .. nothing showing me just my table. I understan it's not the same table form as that youtube clip but how should I do have the same functionality as him.
<!DOCTYPE html>
<html>
<head>
<title>Countries</title>
<meta charset="utf-8" />
<script src="Scripts/jquery-3.1.1.js"></script> // Tried even with jquery-1.12.4.js
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<table class="table table-bordered table-hover table table-responsive success" id="countriesTable">
<thead>
<tr>
<th>
Country Id
</th>
<th>
Country name
</th>
<th class="col-md-2">
Action
</th>
</tr>
</thead>
<tbody class="tbody"></tbody>
</table>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
$('#countriesTable').DataTable({
"bSort": true,
"bFilter": true,
"bPaginate": true,
"bProcessing": true
});
loadCountries();
}
function loadCountries() {
$('#compTable').DataTable({
"bSort": true,
"bFilter": true,
"bPaginate": true,
"bProcessing": true
});
$.ajax({
url: "/Api/Countries",
type: "GET",
headers: {
'Authorization': 'Bearer ' + sessionStorage.getItem('accessToken')
},
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.CountryId + '</td>';
html += '<td>' + item.CountryName + '</td>';
html += '<td><Button class="btn btn-primary" onclick="return getByID(' + item.CountryId + ')">Edit</button> <Button class="btn btn-danger btn-md" onclick="return Delete(' + item.CountryId + ')">Delete</Button></td>';
html += '</tr>';
});
$('.tbody').html(html);
},
error: function (jqXHR) {
if (jqXHR.status == "401") {
$('#errorModal').modal('show');
}
else {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
}
});
}
</script>

You have to initialize the table correctly and also add proper dependent library from the documentation page. To get you started
$('#countriesTable').DataTable({
"bSort": true,
"bFilter": true,
"bPaginate": true,
"bProcessing": true
})
For the small arrow buttons in the column heads (which indicates sorting direction etc.) you need to add proper glyphicon libraries.
You can learn more options here.
How to find the proper dependent library?
Check this example. In the example section there 3 parts HTML, CSS and javascript. They mentioned the libraries there. You need to add them in the correct order they are mentioned.
As per your requirement you need to feature that dattable provides with table generation. After ajax call is made a response is found. Now you get the data from it and map it to appropriate columns.
$('#my-table').DataTable({
ajax: {
url:websiteurl,
data:function(dtl){
}
},
columns: [
{ data: 'col1'},
{ data: 'col2'},
]
});
HTML:
<table id ="my-table" class="table table-striped table-responsive sorting " >
<thead>
<tr>
<td>col1</td>
<td>col2</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
Remember
For this you hvae to build the json output in the fom of array of objects.
JSONArray ja= new JSONArray();
JSONObject jo = new JSONObject();
jo.put("col1",col1val);
jo.put("col2",col2val);
ja.put(jo);
return ja in the response.
You might think
Can I put a html button code in a json string ..yes you can. Try that.
Referrence:Link

Related

How to change the data-source for a table on dropdown-list change

I just can't find any examples that can help me. I have a drop-down list of customers and a table which displays services/products a customer provides. On page load the ddl is set to customer 0 and that customer's data is displayed in the table. I now need to changed the data-source and refresh the table when the drop-down is changed.
The main bits of my code are...
<div class="card-body">
<div class="row">
<div class="col-4">
<lable for="customerFilter" class="control-label">Customer Filter: </lable>
</div>
<div class="col-8">
<input id="customerFilter" class="form-control" />
</div>
</div>
<div id="toolbar">
<div class="alert alert-info">You can refine this list by entering an additional filter in the search box on the right. Any text you type will filter the list based on any of the fields containing the text typed.</div>
</div>
<div>
<table id="table"
data-classes="table table-hover table-condensed"
data-striped="true"
data-toolbar="#toolbar"
data-pagination="true"
data-click-to-select="true"
data-search="true"
data-show-export="true"
data-show-pagination-switch="true"
data-show-toggle="true"
data-show-columns="true"
data-url='#Url.Content("~/SSTCodes/GetSSTCodesByCustomer?CustomerID=0")'>
<thead>
<tr>
<th data-field="sstID" data-formatter="btnViewFormatter" data-sortable="true">ID</th>
<th data-field="sstRU" data-sortable="true" data-formatter="sstFormatter">Recoverability</th>
<th data-field="sstProductCode" data-sortable="true">Product Code</th>
<th data-field="sstProductName" data-sortable="true">Product Name</th>
<th data-field="sstStockLevel" data-formatter="lowStockFormatter">Stock Level</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<script type="text/javascript">
cData = #Html.Raw(ViewData("Customers"));
$("#customerFilter").kendoComboBox({
dataTextField: "Text",
dataValueField: "Value",
change: customerFilterChanged,
dataSource: cData,
filter: 'contains'
});
function customerFilterChanged() {
// NEED TO CHANGE THE DATASOURCE Url
var customer = this.value()
var url = '#Url.Content("~/SSTCodes/GetSSTCodesByCustomer?CustomerID=")' + customer;
// NEED TO SET THIS AS THE TABLES data-url AND REFRESH THE DATASOURCE....
}
var $table = $('#table');
function btnViewFormatter(value) {
return '<a class="btn btn-primary btn-sm" href="#Url.Content("~/SSTCodes/Edit?id=")' + value + '">' + value + '</a>';
}
function sstFormatter(value) {
//Removed for clarity
Return value
}
function lowStockFormatter(value) {
//Removed for clarity
Return value
}
function getSelectedRow() {
var index = $table.find('tr.success').data('index');
return $table.bootstrapTable('getData')[index];
}
$(function () {
$table.bootstrapTable({
fixedColumns: true,
fixedNumber: 1,
exportDataType:"all",
exportTypes:['csv', 'txt', 'xlsx']
});
$table.on('click-row.bs.table', function (e, row, $element) {
$('.success').removeClass('success');
$($element).addClass('success');
});
$table.on('dbl-click-row.bs.table', function (e, row, $element) {
var url = '#Url.Content("~/SSTCodes/Edit?id=")' + getSelectedRow().sstID;
window.open(url, '_self');
})
});
</script>
The function customerFilterChanged is where I need help.
I have changed my approach...
The customerFilterChange function now just redirects the page
function customerFilterChanged() {
window.location.href = "#Url.Content("~/SSTCodes/Index?id=")" + this.value();
}
The controller has been amended so that it has an optional id...
Function Index(Optional id As Integer = 0) As ActionResult
If IsNothing(id) Then
ViewData("CustomerID") = 0
Else
ViewData("CustomerID") = id
End If
ViewData("Customers") = Newtonsoft.Json.JsonConvert.SerializeObject(CustomerModel.CustomerDDLList.GetAllCustomers())
Return View()
End Function
And the data-url value for the table is now
data-url='#Url.Content("~/SSTCodes/GetSSTCodesByCustomer?CustomerID=") + #ViewData("CustomerID")' >
Job done...

KnockoutJs : ko.mapping.fromJS and binding => how to do it properly?

I really am struggling with something that I thought was simple...
I am making a simple search-result table based on $.getJSON call, and want to keep my code as "generic" as possible.
In my (simplified) HTML :
<form id="searchForm">
(...)
<button type="button" onclick="search()">Search</button>
</form>
(...)
<tbody data-bind="foreach: data">
<tr>
<td data-bind="text: FOO"></td>
(...)
<td data-bind="text: BAR"></td>
</tr>
</tbody>
Then in my javascript (in script tags lower in the page):
var search = function(){
var form = $('#searchForm');
$.getJSON("php/query/jsonQuery.php?jsonQuery=search", form.serialize(), function(jsonAnswer, textStatus) {
console.log(jsonAnswer);
if(typeof viewModel === 'undefined'){
var viewModel = ko.mapping.fromJS(jsonAnswer);
ko.applyBindings(viewModel);
}
else{
ko.mapping.fromJS(jsonAnswer, viewModel);
}
$('#divResults').show();
// console.log(viewModel)
});
}
This works fine on the first "search" click... but not the following : Error You cannot apply bindings multiple times to the same element.
As you can guess, this very ugly "if" testing viewModel is a desperate attempt to get rid of that error.
I've tried many things but I just can't figure out how to do it properly...
I've read this Knockout JS update view from json model and this KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element but it didn't help me much... maybe because the search() function isn't called on load (and indeed shouldn't be).
Any KO master to give me a clue? Thanks in advance for your help!
This is how I would be approaching what you are trying to accomplish.
var searchService = {
search: function(form, vmData) {
//$.getJSON("php/query/jsonQuery.php?jsonQuery=search", form.serialize(), function(jsonAnswer, textStatus) {
var jsonAnswer = [{
FOO: "Item 1 Foo",
BAR: "Item 1 Bar"
}, {
FOO: "Item 2 Foo",
BAR: "Item 2 Bar"
}]
ko.mapping.fromJS(jsonAnswer, [], vmData);
//})
}
};
var PageViewModel = function() {
var self = this;
self.data = ko.observableArray();
self.hasResults = ko.pureComputed(function() {
return self.data().length > 0;
});
self.search = function() {
var form = $('#searchForm');
searchService.search(form, self.data);
};
};
ko.applyBindings(new PageViewModel());
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<form id="searchForm">
<button type="button" data-bind="click:search">Search</button>
</form>
<div data-bind="visible: !hasResults()"><b>No Results</b></div>
<div data-bind="visible: hasResults">
<table class="table">
<thead>
<tr>
<td>FOO</td>
<td>BAR</td>
</tr>
</thead>
<tbody data-bind="foreach: data">
<tr>
<td data-bind="text: FOO"></td>
<td data-bind="text: BAR"></td>
</tr>
</tbody>
</table>
</div>
<br/>
<pre><code data-bind="text: ko.toJSON($root)"></code></pre>

get table column value of selected row in table asp.net in jQuery

I am working on asp.net mvc project.
I want to get the cell value from the selected row (row in which "Manage "button is clicked).
in this case value of userID.
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th width="45%">User ID</th>
<th width="45%">User Name</th>
<th width="5%">View</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.TypeList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.UserId)
</td>
<td>
#Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
<input id="Manage2" class="btn btn-primary" type="button" value="Manage" />
</td>
</tr>
}
</tbody>
I am calling jQuery click function and Ajax call and want to send the UserId value in data from selected row to the controller.
below is the jQuery ajax call,
<script type="text/javascript">
$(document).ready(function () {
$('#Manage2').click(function () {
//alert(1);
var url = '#Url.Action("ManageUserRole", "UserRoleCompany")';
$.ajax({
url: url,
data: { Id: '1' },
cache: false,
type: "POST",
success: function (data) {
$("#Data").html(data);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
});
</script>
Below is the view screen shot,
You can actually store the UserId value with html 5 data attribute on the button itself.
Your current code has Id attribute value hard coded inside a loop, which will create more than one element with same Id value. That is invalid HTML!
Remove the Id and use a more generic selector to wire up the click event. Here I added another CSS class "manage" to the button.
<input data-userid="#item.UserId" class="btn btn-primary manage"
type="button" value="Manage" />
and now
$(document).ready(function () {
$('.manage').click(function () {
var id = $(this).data("userid");
alert(id);
// use id for your ajax call
});
});
You do not necessarily need to add the extra css class only to use that as the selector later. Since you are adding a data attribute, you may simply use that as well for your jQuery selector.
$(function () {
$('[data-userid]').click(function () {
var id = $(this).data("userid");
alert(id);
// use id
});
});
You have invalid html because of the duplicate id attributes in your button.
Remove the id="Manage2" and replace with a class name and data- attribute for the value
<input data-id="#item.UserId" class="btn btn-primary Manage2" type="button" value="Manage" />
Then in the script, get the value using
$('.Manage2').click(function () { // class selector
var id = $(this).data('id);
var url = '#Url.Action("ManageUserRole", "UserRoleCompany")';
$.ajax({
url: url,
data: { Id: id },
....
Alternatively you could use relative selectors
$('.Manage2').click(function () {
var id = $(this).closest('tr').children('td:first').text();
....

MVC4-Refresh Issue:Same partial view called 3 times using foreach..loop

I am in a tricky situation,
Scenario- There are gadgets which are to be shown in mobile site.
2.One of the gadget is RSS which user can add multiple times for different topics like one for security, one for news, one for events.
3. So we have 1 partial view for RSS, but if the user has 2 RSS gadgets then the same partial view should load with different gadget name. Here the functionality is working fine using foreach loop.
#foreach (var rssFeed in Model.RSSFeedList)
{
<article class="bm2014_bigBoxWrap bm2014_bigBoxRSS bm2014_paginate">
<img src="~/Content/images/iconRefresh.png" width="20" height="20" alt="refresh icon" title="refresh icon">
<div class="bm2014_expColCtrl">
<h1 class="bm2014_bigBoxHdr">
<span class="bm2014_hiddenHdr"> </span>
<!-- for markup validation -->
#if (rssFeed.Channel.Name == "xyznews")
{
<span>#Html.Label(Labels.Title_xyz)</span>
}
else if(rssFeed.Channel.Category=="xyzRSSFeed")
{
<!--<span>#Html.Label(Labels.xyz) - #rssFeed.Channel.Title</span>-->
<span>#rssFeed.Channel.Title</span>
}
<span class="bm2014_expColBtn"><img src="~/Content/images/iconPlus.png" width="32" height="32" alt="expand collapse icon" title="expand collapse icon"></span>
</h1>
<div class="bm2014_expColContent bm2014_bellnetRSSWrapper" id="bm2014_divBellnetRSS">
#Html.Partial("~/Views/Shared/_RSS.cshtml", rssFeed)
</div>
</div>
</article>
}
<!-- RSS Panel end here -->
Problem is with refresh issue
if i hit the refresh button for selected gadget, it is by default taking only one RSS name and loading the content irrespective of different gadget selected.
partialview page code-
#model Models.RSSFeed
#{
Layout = null;
}
<script src="~/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.multilevelpushmenu.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-simple-pagination-plugin.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.dataTables.js" type="text/javascript"></script>
<script type="text/javascript">
/* scripts to load after the DOM gets ready */
$(function () {
offCanvasMenu(); // trigger Javascript controlled OFF canvas menu after AJAX refresh
$.ajaxSetup({ cache: false });
$("article.bm2014_bigBoxRSS #btnRefresh").on('click', function (event) {
var $rssGadgetID = $(this).parents("article.bm2014_paginate").find("div#bm2014_divBellnetRSS");
var $rssGadgetLdr = $rssGadgetID.find("div#bm2014_gadgetLoader");
ajaxLoaderHeightCtrl($rssGadgetID, $rssGadgetLdr);
// AJAX control
$.ajax({
url: '#Url.Action("RefreshBellnetRSS", "Home", new { feedName = Model.Channel.FeedName })',
contentType: 'application/html; charaset=utf-8',
type: 'GET',
dataType: 'html',
success: function (result) {
$rssGadgetLdr.fadeOut(100, function () {
$rssGadgetID.html(result);
var moveRSS = $("article.bm2014_bigBoxWrap").css("float");
if (moveRSS == "left") {
mQueryAJAX("portrait", $rssGadgetID);
}
else if (moveRSS == "none") {
if (window.matchMedia("(orientation: portrait)").matches) {
mQueryAJAX("portrait", $rssGadgetID);
}
if (window.matchMedia("(orientation: landscape)").matches) {
mQueryAJAX("portrait", $rssGadgetID);
}
}
hideTableHeader();
});
},
error: function (xhr, status) {
alert(status);
}
});
});
});
</script>
<div class="bm2014_gadgetLoader" id="bm2014_gadgetLoader" style="display: none;">
<img src='#Url.Content("~/Content/Images/loaderGadget.gif")' width="48" height="48" alt="ajax loader image" title="ajax loader image">
</div>
<div class="bm2014_strategyContent">
#if (Model.url != null)
{
<table>
<thead>
<th>dummy header - to be hidden</th>
</thead>
<tbody>
#foreach (var url in Model.url)
{
<tr>
<td>
#url.Name
</td>
</tr>
}
</tbody>
</table>
}
</div>
need help/suggestions
If I understand correctly, you need to have 3 refresh buttons for 3 RSS gadgets e.g. one for security, one for news, one for events.
In the current example, every time you call the code to apply click event, you replace the earlier event and the 'feedname' parameter in url for ajax call also gets updated.
$("article.bm2014_bigBoxRSS #btnRefresh").on('click', function (event) {
......
}
You need to be able to distinguish between the refresh buttons and pass correct parameters. One way is to use data-feedname attribute on your btnRefresh anchor tag (if using HTML5)

Play animation with animate.css when removing item

I am using this CSS file http://daneden.github.io/animate.css/ to add some animation to the web site I am building.
The thing is I need to play an animation when I delete an item from a list for example, but how can I do that since the element is no longer in the DOM?
All right,
here is my jsp code:
<tbody class="filter">
<c:forEach var="message" items="${messages}">
<tr id="${message.id}" class="body">
<td>${message.name}</td>
<c:choose>
<c:when test="${not empty message.file}"><td>${message.file.name}</td></c:when>
<c:otherwise><td>${message.tts}</td></c:otherwise>
</c:choose>
<td class="icon"><i id="delete" class="icon-trash icon-hover"></i></td>
</tr>
</c:forEach>
</tbody>
And some jQuery:
$.ajax({
type: "GET",
url: "message/delete/" + id,
dataType: "json",
success: function(response) {
if (response.status == "OK") {
$row.addClass('animated flipOutX');
// Here I need to run an animation before I delete the item.
$('#messageTable tr#' + id).remove();
}
}
});
Thank you again for your help!
UPDATE:
Demo http://jsfiddle.net/g3WLM/1/

Resources