I am having problems rendering a gridview with pagination on a modal. Whenever I click other pages, it doesn't render the modal at all. Just text with formatting of the next page. For now, these are the only ones I can show but if you need to see a screenshot of the problem, or the controller, I will try to post it.
There is no problem on getting the pagination to working. The only thing is the view. I call the #modal-container using an action link from INDEX view, and then shows with a gridview data inside. The problem is that when I click the next page of the data, though it goes to the next page, it un-renders all css of the whole page. Just a stripped down formatted-text. How can I update only the gridview?
#Html.ActionLink("Transaction History", "TransactionHistory", "AccountBalance", new { accountID = item.AccountID, page = 1, pageSize = 15 },
htmlAttributes: new
{
onclick = "GetPlayersDetails('" + item.AccountID + "')",
data_target = "#modal-container",
data_toggle = "modal",
#class = "btn btn-xs btn-flat btn-warning"
}).If("AccountBalance", "TransactionHistory")
Here is the onclick AJAX code:
function GetPlayersDetails(accountID) {
console.log('asdasd');
$.ajax({
url: '#Url.Action("TransactionHistory")', //"/Player/GetPlayersByTeam",
dataType: "html",
data: { accountID: accountID },
type: "GET",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
console.log('error');
},
success: function (data) {
$('#qweqwe').html(data);
console.log('success');
}
});
}
Here is the partialview Modal:
<table id="qweqwe" class="table table-hover table-bordered table-striped text-sm ordertable">
<thead>
<tr>
<th width="35%">Transaction Date</th>
<th>Notes</th>
<th>Amount IN</th>
<th>Amount Out</th>
</tr>
</thead>
<tbody id="checkboxTable">
#foreach (var item in Model.History)
{
<tr id="tableRow" class="text-center">
<td><br />#Html.DisplayFor(modelItem => item.TransactionDate)</td>
<td><br />#Html.DisplayFor(modelItem => item.Notes)</td>
<td><br />#Html.DisplayFor(modelItem => item.AmountIn)</td>
<td><br />#Html.DisplayFor(modelItem => item.AmountOut)</td>
<td class="text-center actionTD hidden">
</td>
</tr>
}
</tbody>
</table>
This is the pager on the modal:
#Html.PagedListPager(Model.History, page => Url.Action("TransactionHistory",
new
{
accountID = ViewBag.accountID,
page = page
}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions
{
DisplayPageCountAndCurrentLocation = true,
DisplayItemSliceAndTotal = true,
ItemSliceAndTotalFormat = "Total Records: {2}",
LinkToFirstPageFormat = "First",
LinkToPreviousPageFormat = "Previous",
LinkToNextPageFormat = "Next",
LinkToLastPageFormat = "Last"
},
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "Get",
UpdateTargetId = "qweqwe"
}))
This is the action from my controller:
public ActionResult TransactionHistory(int accountID, int? page)
{
page = page == null ? 1 : page;
DateTime startDate = Convert.ToDateTime("10-26-2018");
DateTime endDate = Convert.ToDateTime("10-29-2018");
var list = BankAccountManagementBusinessLogic.GetDataUpdate(accountID, startDate, endDate, (int)page, pageSize);
int totalRows = list.Count() > 0 ? (int)list.First().TotalRows : 0;
var mylist = new StaticPagedList<spGetAccountTransactionHistory_Result>(list, (int)page, pageSize, totalRows);
TransactionHistorySearchModel searchModel = new TransactionHistorySearchModel();
TransactionHistoryViewModel model = new TransactionHistoryViewModel(searchModel, mylist);
ViewBag.accountID = accountID;
return PartialView(model);
}
Now, these codes work. Displaying the modal and the gridview. The problem is that when going to the next page, the css of the whole page disappears, just a formatted text of the second page is showing. I am unable to find a solution for this yesterday, hoping for an input. Thanks
Related
I'm trying to use an editable bootstrap table where in data can be inserted on the database. However, I find it difficult since I'm only new with this field. I can load the data from the database and edit the table field but I don't know how can I insert it on the database.
Below is my code for the table. For the <tbody, I used javascript and ajax to load the data from the database. Note that, it only loads the CATEGORY ID and DESCRIPTION. The AMOUNT must be inserted by the user.
<div id="table" class="table-editable">
<table class="table table-sm table-striped table-hover" id="tbl-fees">
<thead>
<tr>
<th>CATEGORY</th>
<th style="display:none">CATEGORY ID</th>
<th scope="col">DESCRIPTION</th>
<th scope="col" class="text-right">AMOUNT</th>
</tr>
</thead>
<tbody id= "fees_table"></tbody>
</table>
</div>
As per the resources online, it says that I can use contenteditable="true" for me to have an editable table.
<script>
function load_fees_list()
{
var sy_id=2;
$.ajax({
method:"GET",
url: "<?php echo site_url(); ?>Get-FCP/"+sy_id,
success: function(response){
$.each(response.fcp_data, function(key, value){
$('#fees_table').append('<tr>\
<td style="display:none">'+value["fc_desc"]+'</td>\
<td id="fc_id">'+value["fc_id"]+'</td>\
<td id="fcp_description">'+value["fcp_description"]+'</td>\
<td id="fmf_amount" class="text-right" contenteditable="true">'+0+'</td>\
</tr>');
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
}
});
}
</script>
I found a script online where it shows the output of the live table when button is clicked.
var $TABLE = $('#table');
var $BTN = $('#export-btn');
var $EXPORT = $('#export');
// A few jQuery helpers for exporting only
jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;
$BTN.click(function () {
var $rows = $TABLE.find('tr:not(:hidden)');
var headers = [];
var data = [];
// Get the headers (add special header logic here)
$($rows.shift()).find('th:not(:empty)').each(function () {
headers.push($(this).text().toLowerCase());
});
// Turn all existing rows into a loopable array
$rows.each(function () {
var $td = $(this).find('td');
var h = {};
// Use the headers from earlier to name our hash keys
headers.forEach(function (header, i) {
h[header] = $td.eq(i).text();
});
data.push(h); //adds new items to the end of an array
});
// Output the result
$EXPORT.text(JSON.stringify(data));
});
However, I can't insert it on the database. I'm planning of inserting the data in a new MySQL table in which it stores the description and amount. Can someone help me on how can I insert it?
I want to display data in table on inserting data as well as when the page is loaded. Storing data successfully works with the code but the issue is;
When I use POST, the form data is completely visible in the URL.
How do i display all data passed in json format in html table.
HTML:
<table class="table table-striped table-bordered" id="myTable">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Match</th>
<th scope="col">Match Date</th>
<th scope="col">Winner</th>
<th scope="col">Loser</th>
<th scope="col">Man of the Match</th>
<th scope="col">Bowler of Match</th>
<th scope="col">Best Fielder</th>
</tr>
</thead>
</table>
JAVASCRIPT:
<script>
$(function() {
$("#submit").on("click", function(e) {
var team_one = $('#team_one').val();
var team_two = $('#team_two').val();
var match_summary = $('#match_summary').val();
var match_date = $('#match_date').val();
var winner = $('#winner').val();
var loser = $('#loser').val();
var man_of_the_match = $('#man_of_the_match').val();
var bowler_of_the_match = $('#bowler_of_the_match').val();
var best_fielder = $('#best_fielder').val();
$.ajax(
{
type: "POST", //HTTP POST Method
url: '<?php echo base_url(); ?>/MatchController/storeMatch',
data: { //Passing data
'team_one': team_one,
'team_two': team_two,
'match_summary' : match_summary,
'match_date' : match_date,
'winner' : winner,
'loser' : loser,
'man_of_the_match' : man_of_the_match,
'bowler_of_the_match' : bowler_of_the_match,
'best_fielder' : best_fielder
},
success: function (response) {
console.log("Response: " + response);
alert("Data stored successfully");
},
});
});
});
//FETCH ALL MATCH DATA USING PASSED API IN CONTROLLER
$(document).ready(function (){
getData();
function getData(){
$.ajax({
url : "<?php echo base_url(); ?>/MatchController/fetchMatchData",
method : 'get',
dataType: "json",
success: function(data){
}
});
}
});
CONTROLLER:
public function storeMatch()
{
$team_one = $_POST['team_one'];
$team_two = $_POST['team_two'];
$match_date = $_POST['match_date'];
$match_summary = $_POST['match_summary'];
$winner = $_POST['winner'];
$loser = $_POST['loser'];
$man_of_the_match = $_POST['man_of_the_match'];
$bowler_of_the_match = $_POST['bowler_of_the_match'];
$best_fielder = $_POST['best_fielder'];
$data = array(
'team_one' => $team_one,
'team_two' => $team_two,
'match_date' => $match_date,
'match_summary' => $match_summary,
'winner' => $winner,
'loser' => $loser,
'man_of_the_match' => $man_of_the_match,
'bowler_of_the_match' => $bowler_of_the_match,
'best_fielder' => $best_fielder
);
$this->MatchModel->saveMatchData($data);
}
public function fetchMatchData()
{
$match_data = $this->MatchModel->fetchMatchList();
return $match_data;
}
Try to pass the result to <tbody> use JQuery
success: function(data){
//delete old tbody block
$('#myTable tbody').remove()
//add tbody block
$('#myTable').append('<tbody><tr><td>'+data.someValue+'</td></tr></tbody>')
}
And when you want add new data just call your getData().
success: function (response) {
getData()
console.log("Response: " + response);
alert("Data stored successfully");
},
Also look at e.preventDefault for your ajax call. If you use ajax needlessly reload page
I am having a simple table which shows basic details about cusotmers. Each customer belongs to one of available customer groups. I also have a dropdown on the top of it where I can toggle between available customer groups and want to update the table with customers belonging to that particular group. Right now everything happens using page reload which is quite inefficient I know. Is there a way to use js here and make only the table section refresh without reloading the entire page.
#GetMapping(WebControllerConstants.RIDER_MAPPING)
public ModelAndView riderMapping(#RequestParam(value = "groupId", required = false) String groupId) {
String group = "1";
if (groupId != null) {
group = groupId;
}
ModelAndView model = new ModelAndView("riderGroupDetails");
model.addObject("list", riderService.findRiderByGroupId(group));
model.addObject("riderGroupList", riderGroupService.findAllGroups());
return model;
}
<select id="category" name="category" onchange="GetAllDetails(this.value);">
//some options here
</select>
<table class="table table-striped table-bordered zero-configuration dataTable">
<thead>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
<th>Mobile No</th>
</thead>
<tbody>
<c:set var="id" value="${1}" />
<c:forEach var="rider" items="${list}">
<tr>
<td>
<c:out value="${id}" />
</td>
<td>
<c:out value="${rider.firstname}" />
</td>
<td>
<c:out value="${rider.lastname}" />
</td>
<td>
<c:out value="${rider.mobile}" />
</td>
</tr>
<c:set var="id" value="${id + 1}" />
</c:forEach>
</tbody>
</table>
<script>
$(window).on(
'load',
function() {
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
if ($.urlParam('groupId') == false) {
} else {
var groupId = $.urlParam('groupId');
console.log('groupId ' + groupId);
$("#category").val(groupId);
}
});
function GetAllDetails(value) {
groupvalue = value;
console.log(groupvalue);
var url = "${context}/rider/mapping?groupId=" + value;
//AJAX works here to send a request but table doesn't refresh.
window.location = url;
}
</script>
//AJAX works here to send a request but table doesn't refresh.
Here your AJAX could listen to a response code. If the code says transaction happened correctly you could create a js function that updates the page info while not refreshing it. The new info can be handled from js from the begining or on the response you can pass the info to be updated and pass it to the redrawing function.
Example:
function updateDBService(request){
var dataStr = JSON.stringify(request);
var url = '/updateDBService';
$.ajax({
url: url,
contentType: "application/json",
data: dataStr,
type: "POST",
statusCode: {
403: function () {
},
404: function () {
},
500: function (data) {
}
},
//This is your response object (data), which you can use to update the onscreen info
success: function (data) {
redrawInfo();
},complete: function(data) {
}
});
}
For this I usually create a controller different from the views controller so I can handle response classes, request classes and all sorts of stuff. Here a controller that uses POST method would be required.
Hopefully this helps you!
I have problem in displaying the content of a table which will be available once an AJAX request is made on click of some row of another table in the same page.
Following is my code for the table in my JSP page.
<table id="previousList" class="table">
<thead>
<tr>
<th colspan="6">Previous Billing Records</th>
</tr>
<tr>
<th>Bill Number</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<c:forEach var="lastBill" items="${previousBills}" varStatus="status">
<tr>
<td>${lastBill.billingId}</td>
<td>${lastBill.billAmount}</td>
</tr>
</c:forEach>
</tbody>
</table>
var jsonData;
var patientTable = $('#patientsList').DataTable();
var table = document.getElementById("selectedPatient");
$('#patientsList tbody').on('click', 'tr', function() {
var data = patientTable.row(this).data();
console.log("Data " + data);
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/billing/lastBill",
data: "patientId=" + data[0],
success: function(response) {
console.log("Showing the LastBill Details: " + response);
jsonData = response;
},
error: function(e) {
alert('Error: ' + e);
}
});
});
My controller code is as follows.
#RequestMapping(value="/lastBill")
public #ResponseBody String lastBill(ModelMap model, String patientId)
{
System.out.println("ID: " + patientId);
Gson gson = new Gson();
Bill b = new Bill();
b.setBillAmount(1000);
b.setBillingId("12345SDf");
Collection<Bill> bills = new ArrayList<Bill>();
bills.add(b);
model.addAttribute("previousBills",bills);
String jsonBills = gson.toJson(bills);
model.addAttribute("jsonBills", jsonBills);
return jsonBills;
}
I am able to get the JSON data but failed to bind the values to the table. Any suggestions/answers would be appreciable. Thanks in advance.
try this it should work.
var jsonData;
$('#patientsList tbody').on('click', 'tr', function() {
var data = patientTable.row(this).data();
console.log("Data " + data);
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/billing/lastBill",
data: "patientId=" + data[0],
success: function(response) {
console.log("Showing the LastBill Details: " + response);
jsonData = JSON.parse(response);
$.each(jsonData, function(i, bill) {
var newRowContent = "<tr><td>"+bill.billingId+"</td><td>"+bill.billAmount+"</td></tr>";
$("#previousList tbody").append(newRowContent);
});
},
error: function(e) {
alert('Error: ' + e);
}
});
});
This is front end,
<div class="uk-width-1-4 ">
<table class="uk-table uk-table-striped uk-table-hover" id="tabledata">
<thead>
<tr>
<th><input type="checkbox" ></th>
<th>Site ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" id="chkall" value="<%= d.siteid%>">
</td>
<td><%=d.siteid%></td>
</tr>
<% });
} %>
</tbody>
</table>
</div>
This is backend,
var user_id=req.query.user_id;
var siteid=req.query.chkall;
console.log("chkall =="+siteid);
sql="UPDATE site SET userid='"+user_id+"' WHERE siteid IN('"+siteid+"')";
}
getSQLData(sql, function(resultsets){
console.log("user...sql"+sql);
userresults = resultsets;
});
You can use it like this:
$("input[type='checkbox']").val();
Hope will help you.
If you are doing form submit, and if the check-box un-checked the false value will not go to the back-end. You should have some hidden value if check box un-checked.
If it is ajax call, you can get checkbox value as like below
$("input[type='checkbox']").val();
or
$("#checkboxid").val();
If you submit form then write name tag. And if you send data from ajax then get value by element id then send to server.
You do like this..
var chk = document.getElementById(checkboxid).checked;
if (chk == true) {
var chkval=$("#checkboxid").val();
}
If you have in list then do loop and add to a global variable and use that variable.
//check box
<asp:CheckBox ID="chkpermission" runat="server" onclick="checking(this.id);" Checked='<%# Convert.ToBoolean(Eval("permission")) %>' />
<script type="text/javascript">
function checking(id) {
$('#ctl00_ContentPlaceHolder1_lblresponce').val('');
if (id) {
ids = id.split('_');
var chkval = document.getElementById(id).checked;
var TitleId = "ctl00_ContentPlaceHolder1_grdpermissions_" + ids[3] + "_hdntitleid"; //here i am getting the value from the grid
var pagePath = window.location.pathname;
var param = JSON.stringify({ "TitleId": itleId,"chkval":chkval });
$.ajax({
type: "POST",
url: pagePath + "/updatevalue",
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != null) {
var result = data.d;
$('#ctl00_ContentPlaceHolder1_lblresponce').text('Updated successfully');
}
},
error: function () {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
}
}
</script>
in the back end code
[WebMethod]
public static Boolean updatevalue( string TitleId, string chkval)
{
Boolean flag = false;
if ( TitleId != "" && chkval !="")
{
//Update your your query here with single id...
flag=true;
// return flag if updated
}
return flag;
}
I hope it works in your case.