Laravel move row data from table to another table using button - javascript

Just to have an example. After I click the button it should move the row into another table in the database just like it is shown here and delete it afterwards. After I click the approve button the data row should transfer to another table in database. I really don't know how to start something like this in Laravel and I really can't find something related.
Refer to this image
Here's my view.blade.php
<table class="table table-striped table-bordered tbl_pendingres" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th hidden>Id</th>
<th>Name</th>
<th>Equipment</th>
<th>Reservation Date</th>
<th>Room</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($app as $resdata)
<tr>
<td hidden>{{$resdata->id}} </td>
<td>{{$resdata->name}}</td>
<td>{{$resdata->Name_item}}</td>
<td>{{$resdata->dt_item}}</td>
<td>{{$resdata->room_item}} </td>
<td>
<form action="admin.reservations.store{{ $resdata->id}}" method="POST">
{{ csrf_field() }}
<button type="submit" class="btn btn-primary btn-sm">
Accept
<i class="fas fa-chevron-right"></i>
</button></a>
</form>
<button type="button" class="btn btn-danger btn-sm">
Cancel
<i class="fas fa-times"></i>
</button>
</td>
</tr>
#endforeach
</tbody>
</table>
Here's my reservation controller
public function store($id)
{
$first = Reservation::find($id); //this will select the row with the given id
// now save the data in the variables;
$ab = $first->name;
$cd = $first->Name_item;
$ef = $first->dt_item;
$gh = $first->room_item;
$ij = $first->ldate_item;
$second = new AcceptedReservation();
$second->a_name = $ab;
$second->a_nitem = $cd;
$second->a_ditem = $ef;
$second->a_ritem = $gh;
$second->a_ldateitem = $ij;
$second->save();
// then return to your view or whatever you want to do
return view('admin.reservations.index')->with('message','Reservation Accepted');
}
Also when I clicking the button it always having error
Too few arguments to function
App\Http\Controllers\Admin\ReservationsController::store(), 0 passed in C:\laragon\www\ecmtech\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 1 expected

keep the store function empty remove $id also .like this
public function store()
{
// do nothing
}
Create a new function like this in the controller
public function acceptReservation(Request $request, $id)
{
$first = Reservation::find($id); //this will select the row with the given id
//now save the data in the variables;
$ab = $first->name;
$cd = $first->Name_item;
$ef = $first->dt_item;
$gh = $first->room_item;
$ij = $first->ldate_item;
$second = new AcceptedReservation();
$second->a_name = $ab;
$second->a_nitem = $cd;
$second->a_ditem = $ef;
$second->a_ritem = $gh;
$second->a_ldateitem = $ij;
$second->save();
/// IF YOU NEED TO REMOVE 1st TABLE VALUE
$first->delete();
//then return to your view or whatever you want to do
return redirect()->route('admin.reservations.index')->with('message','Reservation Accepted');
}
now DEFINE The ROUTE Like this
Route::post('reservation-accept/{id}', [ReservationsController::class,'acceptReservation'])->name('reservation.accept');
Now where you are adding the accept button add it call it like this
<form action="{{route('admin.reservation.accept',$resdata->id)}}" method="POST">
#csrf
<button type="submit" class="btn btn-primary btn-sm" >Accept <i class="fas fa-chevron-right"></i></button></a>
</form>

Related

Need idea to use variable JS outside and use button to send data

This script save the id of the row I clicked. But now I would like to do :
"If I click on buttonmodif then change url and send the variable number (which is the id of the row) into the url (and the next page) . I'm not sure how to do it.
I would like to save the variable number outside the script and when I click on buttonmodif I send my variable to another url.
Thank you for your answer!
HTML FILE :
<div id="page-wrapper" style=" padding-left: 20px">
<form method="post" name="employes1" action="employes.php">
<div class="container-fluid">
<div class="row">
<div class=" text-center">
<button type="button"
class="btn btn-default"><?php echo '<a href="employesajout.php" > Ajouter un employé </a>'; ?></button>
<button type="submit" name="buttonmodif" id="modifon"> Mofidier informations</button>
<button type="submit" class="btn btn-default">Supprimer employé</button>
<button type="button" class="btn btn-default">Créer un contrat de travail</button>
</div>
</div>
<div class="row table-responsive">
<table class="table table-bordered table-hover" id="MyTable">
<thead class="-inverse">
<?php
$rep = $bdd->prepare('SELECT * from employee');
$rep->execute();
$resultat = $rep->fetchAll();
?>
<tr>
<th>#</th>
<th>Nom</th>
<th>Prénom</th>
<th>Résidence</th>
<th>NAS</th>
<th>Date d'entré</th>
<th>Heure /semaine</th>
<th>Salaire brute</th>
<th>Salaire net</th>
<th>Vacance (s)</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php foreach ($resultat as $row) {
echo "
<tr class ='clickable-row'>
<td>$row[0]</td>
<td>$row[1]</td>
<td>$row[2]</td>
<td>$row[3]</td>
<td>$row[4]</td>
<td>$row[5]</td>
<td>$row[6]</td>
<td>$row[7]</td>
<td>$row[8]</td>
<td>$row[9]</td>
<td>$row[10]</td>
</tr>";
};
?>
<script>
$(document).ready(function ($) {
$(".clickable-row").click(function () {
var number = parseInt($(this).closest('tr').children().eq(0).text());
console.log(number);
});
// active click hilight
$('td').click(function () {
$('tr').removeClass('active');
$(this).parent().addClass('active');
});
});
</script>
</tbody>
</table>
</div>
</div>
</form>
</div>
Declare the variable outside the click function. Then bind a click handler on the buttonmodif button that uses the variable. You can add a type="hidden" input to the form, and put the value there.
$(document.ready(function() {
var number;
$(".clickable-row").click(function() {
number = parseInt($(this).closest('tr').children().eq(0).text());
console.log(number);
});
$("#modifon").click(function() {
$("#hiddenfield").val(number);
});
});

angular $http post return on success [duplicate]

This question already has answers here:
How to $http Synchronous call with AngularJS
(7 answers)
Closed 5 years ago.
Hi Everyone I have the following due to some situation on one of my projects.
I'm working with angular-xeditable, it has a method onbefore save which should returns a string in case I want the from to maintain opened(editable) and true in case I want to form to be closed(not editable).
Now the problem, below you will find my code for one angular function
self.validateBeforeSave = function(data, id){
var current_id = id;
$http.post('data/functions.php', {
action : 'updateQuotasDisease',
sqlPeriod : data.period,
sqlDiseaseCode : data.disease_code,
sqlTargetCountry : data.target_country,
sqlTargetSpecialty : data.target_specialty,
sqlChartsAmount : data.charts_amount,
sqlAmount : data.amount,
sqlStatus : data.status
})
.success(function(response) {
if(response == 'quota-exists'){
$("#"+current_id).css("background-color", "#ffc4c4");
swal("That quota already exists!", "", "error");
return "error-msg";
}
else{
$("#"+current_id).css("background-color", "#ffffff");
return true;
}
})
.error(function(response) {
console.log('Error: ' + response);
});
};
This code is being called from this HTML, but basically what matters is the need of a return from previous functions of true or "string", you can find onbeforesave="$ctrl.validateBeforeSave($data, line.id)" from there I'm calling the previous function.
<table class="table general-tables table-responsive" ng-show="$ctrl.VisibleQuotasDisease">
<thead>
<tr>
<th>Actions</th>
<th>Period</th>
<th>Disease code</th>
<th>Target country</th>
<th>Target specialty</th>
<th>Charts amount</th>
<th>Amount</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="line in $ctrl.quotasDisease" id="{{line.id}}">
<td style="white-space: nowrap">
<!-- onaftersave="$ctrl.saveRowDisease($data, line.id, line) validateBeforeSave" -->
<form editable-form name="rowform" onbeforesave="$ctrl.validateBeforeSave($data, line.id)" ng-show="rowform.$visible" class="form-buttons form-inline" shown="inserted == line">
<button type="submit" ng-disabled="rowform.$waiting" class="btn btn-xs btn-primary">
<i class="fa fa-2x fa-save"></i>
</button>
<button type="button" ng-disabled="rowform.$waiting" ng-click="rowform.$cancel()" class="btn btn-xs btn-default">
<i class="fa fa-2x fa-close"></i>
</button>
</form>
<div class="buttons" ng-show="!rowform.$visible">
<button class="btn btn-xs btn-warning" ng-click="rowform.$show()">
<i class="fa fa-2x fa-edit"></i>
</button>
<button class="btn btn-xs btn-danger" ng-click="$ctrl.removeRowDisease($index, line)">
<i class="fa fa-2x fa-trash-o"></i>
</button>
</div>
</td>
<td>
<span editable-text="line.period" e-class="period-inputs" e-name="period" e-form="rowform" e-maxlength="7" e-required>
{{line.period}}
</span>
</td>
<td>
<span editable-text="line.disease_code" e-name="disease_code" e-form="rowform" e-maxlength="2" e-required>
{{line.disease_code}}
</span>
</td>
<td>
<span editable-text="line.target_country" e-name="target_country" e-form="rowform" e-maxlength="2" e-required>
{{line.target_country}}
</span>
</td>
<td>
<span editable-text="line.target_specialty" e-name="target_specialty" e-form="rowform" e-maxlength="4" e-required>
{{line.target_specialty}}
</span>
</td>
<td>
<span editable-text="line.charts_amount" e-name="charts_amount" e-form="rowform" e-onkeypress="return onlyInt(event)" e-required>
{{line.charts_amount}}
</span>
</td>
<td>
<span editable-text="line.amount" e-name="amount" e-form="rowform" e-onkeypress="return onlyInt(event)" e-required>
{{line.amount}}
</span>
</td>
<td>
<span editable-text="line.status" e-name="status" e-form="rowform" e-onkeypress="return onlyInt(event)" e-required>
{{line.status}}
</span>
</td>
</tr>
</tbody>
</table>
Finnaly I want to do the question how can I do a return from inside the success section of $http post or how can I workaround to solve this situation.
Thanks in advance.
Just as another piece of code here the php function that I'm calling
if($request -> action == 'updateQuotasDisease'){
$period_sql = $request -> sqlPeriod;
$disease_code_sql = $request -> sqlDiseaseCode;
$target_country_sql = $request -> sqlTargetCountry;
$target_specialty_sql = $request -> sqlTargetSpecialty;
$charts_amount_sql = $request -> sqlChartsAmount;
$amount_sql = $request -> sqlAmount;
$status_sql = $request -> sqlStatus;
$existing_record = connDB() -> getOne("SELECT count(*) FROM quota_period WHERE period_field = '$period_sql' AND disease_code_numeric = '$disease_code_sql' AND targeted_country = '$target_country_sql' AND targeted_specialty_numeric_code = '$target_specialty_sql' AND amount = $amount_sql AND patient_cases_amount = $charts_amount_sql AND status = $status_sql;");
if($existing_record < 1){
connDB() -> query("UPDATE quota_period SET period_field = '$period_sql', disease_code_numeric = '$disease_code_sql', targeted_country = '$target_country_sql', targeted_specialty_numeric_code = '$target_specialty_sql', patient_cases_amount = $charts_amount_sql, amount = $amount_sql, status = $status_sql WHERE period_field = '$period_sql' AND disease_code_numeric = '$disease_code_sql' AND targeted_country = '$target_country_sql' AND targeted_specialty_numeric_code = '$target_specialty_sql';");
}
else{
echo "quota-exists";
}
}
First of all, your return is returning only to success call/caller. It can't be caught outside from success.
The second thought is from the ajax call. http post from angular was written to be always asynchronous. So, your function will never wait for the ajax request be completed.
But you can use the $q module to make the function will "wait" and receive the result to return it.
It's something like this:
function() {
var deferred = $q.defer();
$http.post('data/functions.php', arguments);
.success(function(response) {
//your code
//resolve the promise
deferred.resolve('request successful');
})
.error(function(data,status,headers,config){
//reject the promise
deferred.reject('ERROR');
});
return deferred.promise;
}
You only may to ensured the result which you want from deferred.promise (which I don't know that).
You can see a bit more in these links above:
To then() or to success() in AngularJS
How to $http Synchronous call with AngularJS
how to make synchronous http request in angular js

how to search a user in a bootstrap table of users?

I'm developing an application for users management with spring mvc. I'm using this bootstrap table in my jsppage which make me do a research on the data in the table .
In my table the data of users is retreived from database . this is the code :
<div class="col-md-9">
<form action="#" method="get">
<div class="input-group">
<!-- USE TWITTER TYPEAHEAD JSON WITH API TO SEARCH -->
<input class="form-control" id="system-search" name="q"
placeholder="Search for" required> <span
class="input-group-btn">
<button type="submit" class="btn btn-default">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</form>
<table class="table table-list-search">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Surname</th>
<th>email</th>
<th>contact</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<c:forEach items="${listUsers}" var="user">
<tbody>
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.surname}</td>
<td>${user.email}</td>
<td>${user.contact}</td>
<td>
<p data-placement="top" data-toggle="tooltip" title="Edit">
<button class="btn btn-primary btn-xs" data-title="Edit"
data-toggle="modal"
onclick="location.href='<c:url value="/modifier/${user.id}" />'">
<span class="glyphicon glyphicon-pencil"></span>
</button>
</p>
</td>
<td>
<p data-placement="top" data-toggle="tooltip" title="Delete">
<button class="btn btn-danger btn-xs" data-title="delete"
data-delete='${user.id}' data-toggle="modal"
data-target="#confirm-delete" data-href="/supprimer/${user.id}">
<span class="glyphicon glyphicon-trash"></span>
</button>
</p>
</td>
</tr>
</tbody>
</c:forEach>
</table>
</div>
and this is the script which do the research on the table :
$(document).ready(function() {
var activeSystemClass = $('.list-group-item.active');
//something is entered in search form
$('#system-search')
.keyup(function() {
var that = this;
// affect all table rows on in systems table
var tableBody = $('.table-list-search tbody');
var tableRowsClass = $('.table-list-search tbody tr');
$('.search-sf').remove();
tableRowsClass
.each(function(i, val) {
//Lower text for case insensitive
var rowText = $(val).text().toLowerCase();
var inputText = $(that).val().toLowerCase();
if (inputText != '') {
$('.search-query-sf').remove();
tableBody
.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'
+ $(that).val()
+ '"</strong></td></tr>');
} else {
$('.search-query-sf').remove();
}
if (rowText.indexOf(inputText) == -1) {
//hide rows
tableRowsClass.eq(i).hide();
} else {
$('.search-sf').remove();
tableRowsClass.eq(i).show();
}
});
//all tr elements are hidden
if (tableRowsClass.children(':visible').length == 0) {
tableBody.append('<tr class="search-sf"><td class="text-muted" colspan="6">No entries found.</td></tr>');
}
});
});
but when I've changed to dynamic table I have this result which make the word searching for : repeated n times !
I tried to change the code of the script but I failed to have the right script.
could some one help me please ?
It looks like this might be the problem
tableRowsClass.each(function(i, val) {
//Lower text for case insensitive
var rowText = $(val).text().toLowerCase();
var inputText = $(that).val().toLowerCase();
if (inputText != '') {
$('.search-query-sf').remove();
tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'+ $(that).val()+ '"</strong></td></tr>');
.each means that you're adding <tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'+ $(that).val()+ '"</strong></td></tr> to the start (because it's prepend) of your table, one for every element using .table-list-search tbody tr
try just moving tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'+ $(that).val()+ '"</strong></td></tr>'); outside of the .each() so that it only runs once.
I echo Jamie's answer, but I'd do a bit more refactoring.
I would move the searching out into its own function and pass the required rows collection and search string into it.
I would also move the check for search text outside the each loop, because the value is available outside the loop and doesn't change.
$(document).ready(function() {
var activeSystemClass = $('.list-group-item.active');
var searchTable = function(rows, searchStr){
var searching = false;
rows.each(function(i, val){
var rowText = $(val).text().toLowerCase();
if (rowText.indexOf(searchStr) == -1) {
//hide rows
rows.eq(i).hide();
} else {
$('.search-sf').remove();
rows.eq(i).show();
}
if (rows.children(':visible').length == 0) {
tableBody.append('<tr class="search-sf"><td class="text-muted" colspan="6">No entries found.</td></tr>');
}
}
};
//something is entered in search form
$('#system-search')
.keyup(function() {
var that = this;
// affect all table rows on in systems table
var tableBody = $('.table-list-search tbody');
var tableRowsClass = $('.table-list-search tbody tr');
var inputText = $(that).val();
$('.search-sf').remove();
if (inputText != ''){
$('.search-query-sf').remove();
searchTable(tableRowsClass, inputText.toLowerCase())
tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "' + inputText + '"</strong></td></tr>');
}
});
});
An alternative to using javascript to create the repeating table row could be to use the hidden attribute and use javascript to remove that attribute whenever the .keyup event fires. You can then use javascript to set the value of a span tag with the search query. I couldn't get this example to work on jsFiddle or plunker, but i made an example. (this is pure raw JS with no styling)
<head>
<script type="text/javascript">
function doSearch(){
document.getElementById("searchingForRow").removeAttribute("hidden");
document.getElementById("searching").innerHTML = document.getElementById("system-search").value
}
</script>
</head>
<body>
<div class="col-md-9">
<div class="input-group">
<form>
<div>
<input id="system-search" placeholder="Search for" >
<button type="submit" class="btn btn-default" onclick="doSearch()">
Search
</button>
</div>
</form>
</div>
<table>
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Surname</th>
<th>email</th>
<th>contact</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tr class="search-query-sf" id="searchingForRow" hidden>
<td colspan="6"><strong>Searching for: <span id="searching"></span></strong></td>
</tr>
<tbody>
<tr>
<td>An Example data this does nothing</td>
</tr>
</tbody>
</table>
this example, when the search button is clicked, removed the hidden attribute, making that row visible, and set's the span in the row to the value of the textbox.
it's essentially what you are trying to do.
with this method, it doesn't matter how many times the code to remove the hidden attribute is called, nothing will render more than once.

Disable other rows when editing one row - editing individual row of a table

In the following html code, when one row is in an editing mode(the edit button on this row is clicked), the edit button on the rest of the rows shall be disabled. And when one row is in the edit mode, data will show up in a text input field.
<table class="table">
<thead>
<tr>
<th class="col-sm-4">Branch Name</th>
<th class="col-sm-3">Branch ID</th>
<th class="col-sm-3">Foo</th>
<th class="col-sm-1">Doo</th>
<th class="col-sm-3"></th>
</tr>
</thead>
<tr ng-repeat="branch in branches">
<td id="name" ng-bind="branch.name"></td>
<td id="ID" ng-bind="branch.id"></td>
<td id="foo" data-editable>
<span ng-hide="editMode" ng-bind="branch.foo"></span>
<input class="form-control" data-ng-show="editMode" id="foo" data-ng-model="branch.foo"/>
</td>
<td id="doo" data-editable>
<span ng-hide="editMode" ng-bind="branch.doo"></span>
<input class="form-control" data-ng-show="editMode" id="do" ng-model="branch.doo"/>
</td>
<td>
<button type="submit" class="btn btn-default" data-ng-disabled="editing" data-ng-show="!editMode" data-ng-click="editMode = true; editEntry(branch)">Edit</button>
<span ng-show="editMode" class="pull-right">
<button type="submit" class="btn btn-default" data-ng-disabled="!enableToSave(branch)" data-ng-click="editMode = false; saveEntry(branch)">Save</button>
<button type="submit" class="btn btn-default" ng-show="editMode" data-ng-click="editMode = false; cancelEditing(branch)">Cancel</button>
</span>
</td>
</tr>
</table>
The control mechanics is the "editMode".The Javascript/AngulaJS code is something like the followings:
$scope.editing = false;
$scope.editEntry = function(branch) {
if ($scope.editing !== false) {
...
} else {
$scope.editing = true;
....
}
}
$scope.saveEntry = function(branch){
...
$scope.editing = false;
}
$scope.cancelEditing = function(branch){
if ($scope.editing !== false) {
$scope.editing = false;
...
}
}
$scope.enableToSave = function(branch){
...
}
The approach, however, doesn't seem to be reliable. Any better approaches?
Try to use ng-repeat instance instead of single model
Like this
<button type="submit" class="btn btn-default" data-ng-disabled="branch.isDisable" data-ng-click="saveEntry(branch)">Save</button>
<button type="submit" class="btn btn-default" ng-show="branch.isDisable" data-ng-click="cancelEditing(branch)">Cancel</button>
Create a mapper when click on edit make other disabled
Like this
$scope.editEntry = function(branch) {
branch.isDisable=false;
$scope.branches.forEach(function(x){
if(x.id!=branch.id)
x.isDisable=true;
})
}
You need a parametric check on your table:
<tr ng-repeat="branch in branches" ng-disabled="editingOther(branch.id)">
...
<button type="submit" class="btn btn-default" data-ng-disabled="editing" data-ng-click="editEntry(branch)">Edit</button>
then in Angular
$scope.editing = false;
$scope.editing_entry = null;
$scope.editEntry = function(branch) {
$scope.editing = true;
$scope.editing_entry = branch.id;
}
$scope.editingOther = function(branch_id) {
return $scope.editing && $scope.editing_entry != branch_id;
}
I put a ng-disabled on the tr element as an example, you will need to build your own desired logic for the other rows.

Live search on a web grid table with pagination working only on the actual page

I want to implement a live search on a web grid table which has pagination. However, my search only shows elements which are present in the actual page. I want my search function to do a search on all the element present in the table. Not only the ones actually displayed. Below is my search script:
<script type="text/javascript">
$(document).ready(function () {
$("#filter").keyup(function () {
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
console.log(filter);
// Loop through each row of the table
$("table tr").each(function () {
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
count++;
}
});
/* var numberItems = count;
$("#filter-count").text("Number of Comments = "+count);*/
});
});
my html page:
<div>
<div id="homeMessage">
Please see below the list of books available.
</div>
<br />
<div id="divCurrentRented">
<form id="live-search" action="" class="styled" method="post">
<fieldset>
<input type="text" class="form-control" id="filter" value="" placeholder="Search by title or author..."/>
<span id="filter-count"></span>
</fieldset>
</form>
</div>
<br />
<div id="divCurrentRented">
#{
WebGrid obj = new WebGrid(Model, rowsPerPage: 5);
}
#obj.Table(htmlAttributes: new
{
id="tableCurrentRented",
#class = "table"
},
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
rowStyle: "webgrid-row-style",
columns: obj.Columns(
obj.Column("Title", header: "Title"),
obj.Column("Author", header: "Author"),
obj.Column("Avaible", header: "Available", canSort:false),
obj.Column(header: "Rent", format:#<button type="button" class="btn btn-default">Rent it</button>)
))
</div>
<div style="text-align:right">
#obj.Pager(mode: WebGridPagerModes.All)
</div>
<br />
Any idea of how to do this?
The HTML:
<table id="tableCurrentRented" class="table">
<thead>
<tr class="webgrid-header">
<th scope="col">
Title </th>
<th scope="col">
Author </th>
<th scope="col">
Available </th>
<th scope="col">
Rent </th>
</tr>
</thead>
<tbody>
<tr class="webgrid-row-style">
<td>Le Bossu de Notre Dame</td>
<td>Victor Hugo</td>
<td>Yes</td>
<td><button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" data-id="9" data-title="Le Bossu de Notre Dame">Yes</button></td>
</tr>
<tr class="webgrid-alternating-row">
<td>Oliver Twist</td>
<td>Charles Dickens</td>
<td>Yes</td>
<td><button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" data-id="1" data-title="Oliver Twist">Yes</button></td>
</tr>
<tr class="webgrid-row-style">
<td>Pride and Prejudice</td>
<td>Jane Austen</td>
<td>Yes</td>
<td><button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" data-id="5" data-title="Pride and Prejudice">Yes</button></td>
</tr>
<tr class="webgrid-alternating-row">
<td>Sense and Sensibility</td>
<td>Jane Austen</td>
<td>Yes</td>
<td><button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" data-id="6" data-title="Sense and Sensibility">Yes</button></td>
</tr>
<tr class="webgrid-row-style">
<td>The Mayor of Casterbridge</td>
<td>Thomas Hardy</td>
<td>Yes</td>
<td><button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" data-id="3" data-title="The Mayor of Casterbridge">Yes</button></td>
</tr>
</tbody>
</table>
My controller method:
public ActionResult SearchBooks()
{
var listBook = datamanager.GetAllBooks();
List<ViewBook> listViewBook = new List<ViewBook>();
foreach (Book b in listBook)
{
ViewBook viewBook = new ViewBook();
viewBook.BookID = b.BookId;
viewBook.Title = b.Title;
viewBook.Author = b.Author;
if (b.Rented ?? true)
{
viewBook.Avaible = "No";
}
else
{
viewBook.Avaible = "Yes";
}
listViewBook.Add(viewBook);
}
return View(listViewBook);
}
I have succeeded in passing all the models of my list to the javascript:
var data = #Html.Raw(Json.Encode(Model));
However, when I do this:
$(data).each(function () {
to loop through each element of data, I get this error:
Cannot use 'in' operator to search for 'opacity' in undefined
Any idea how I can solve this?
Javascript
$("#filter").keyup(function () {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: 'Search?q='+$("#filter").val(),
success:
function (result) {
$("#tableCurrentRented tbody").empty();
$.each(result.Books, function (index, item) {
var cls=(index%2==0)?"webgrid-row-style":"webgrid-alternating-row";
var html = ' <tr class="'+cls+'">'+
'<td>'+item.Title +'</td>'+
'<td>'+item.Author +'</td>'+
'<td>'+item.Avaible +'</td>'+
' <td><button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" data-id="'+item.BookID +'" data-title="'+item.Title+'">'+item. +'</button></td></tr>';
$("#tableCurrentRented tbody").append(html);
});
},
error: function (xhr, status, err) {
}
});
});
Add new method for searching in controller
public ActionResult Search(string q)
{
var listBook = datamanager.GetAllBooks().Where(X=> X.Title.Contains(q)).ToList();
List<ViewBook> listViewBook = new List<ViewBook>();
foreach (Book b in listBook)
{
ViewBook viewBook = new ViewBook();
viewBook.BookID = b.BookId;
viewBook.Title = b.Title;
viewBook.Author = b.Author;
if (b.Rented ?? true)
{
viewBook.Avaible = "No";
}
else
{
viewBook.Avaible = "Yes";
}
listViewBook.Add(viewBook);
}
return Json(new { Books = listViewBook }, JsonRequestBehavior.AllowGet);
}
It seems you have a "Model" variable holding the data. Perhaps you should consider filtering the data in this Model directly and passing the filtered Model to the webgrid. The problem, how I understand it, is that you're trying to fetch already rendered values rather than considering the entire collection of data before rendering the filtered data.

Categories