I am new to Django and working on a eCommerce website and trying to improve cart functions.
I follow the course to use JavaScript to update the items in the cart like below code.
If I clicked the "add" or "remove" button on other page(like product list), it works fine.
However, when I tried to lick "remove" button on the cart page (where I can see all the products in the cart), it worked fine as the very first time, the item removed from the cart.
Afterward, I clicked the button, the page just refreshed. Then I clicked another time, it worked again. So it's like after the first item removed, I have to click two times to remove the item I want.
Below are my JavaScript Code, views.py, and my cart_home.html. Hope anyone could help get through this, I've been stuck for a week....
JavaScript
<script type="text/javascript">
$(document).ready(function(){
var productForm = $(".form-product-ajax") // id:#form-product-ajax
productForm.submit(function(event){
event.preventDefault();
console.log("Form is not sending");
var thisForm =$(this);
var actionEndpoint = thisForm.attr('data-endpoint');
var httpMethod = thisForm.attr('method');
var formData = thisForm.serialize();
$.ajax({
url: actionEndpoint,
method: httpMethod,
data: formData,
success: function (data) {
console.log("success");
console.log(data);
console.log("Added:",data.productAdded);
console.log("Removed:",data.productRemoved);
var submitSpan = thisForm.find(".submit-span")
if (data.productAdded) {
submitSpan.html('<button class="btn btn-danger btn-sm " type="submit" name="remove">Remove</button>')
} else {
submitSpan.html('<button class="btn btn-success btn-sm" type="submit" name="Add">Add to Cart</button>')
}
var navbarCount = $(".navbar-cart-count")
navbarCount.text(data.cartItemCount)
var currentPath = window.location.href
if (currentPath.indexOf("cart") != -1) {
refreshCart()
}
},
error: function (errorData) {
console.log("error");
console.log(errorData);
}
})
})
function refreshCart() {
console.log("in current cart");
var cartTable = $(".cart-table")
var cartBody = cartTable.find(".cart-body")
var productRows = cartBody.find(".cart-products")
var currentUrl = window.location.href
var refreshCartUrl ='api/carts'
var refreshCartMethod="GET";
var data={};
$.ajax({
url: refreshCartUrl,
method: refreshCartMethod,
data:data,
success:function(data) {
var hiddenCartItemRemoveForm = $(".cart-item-remove-form")
if (data.products.length>0) {
productRows.html("")
i = data.products.length
$.each(data.products,function (index,value) {
console.log(value);
var newCartItemRemove = hiddenCartItemRemoveForm.clone()
newCartItemRemove.css("display","none")
newCartItemRemove.find(".cart-item-product-id").val(value.id)
cartBody.prepend("<tr><th scope=\"row\">" + i +"</th><td><a href='" +value.url + "'>" + value.name +"</a>" + newCartItemRemove.html() + "</td><td>" + value.price + "</td></tr>")
i --
})
cartBody.find(".cart-subtotal").text(data.subtotal);
cartBody.find(".cart-tax").text(data.tax);
cartBody.find(".cart-total").text(data.total);
}else {
window.location.href = currentUrl;
}
},
error:function(errorData) {
console.log("error");
console.log(errorData);
}
})
}
})
</script>
Cart_home.html
{% extends "base.html" %}
{% block content %}
<h1>Cart</h1>
{% if cart.products.exists %}
<table class="table cart-table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Prodcut Name</th>
<th scope="col">Product Price</th>
</tr>
</thead>
<tbody class="cart-body">
{% for product in cart.products.all %}
<tr class='cart-products'>
<th scope="row">{{forloop.counter}}
<td>{{product.name}}
{% include "carts/snippets/remove-product.html" with product_id=product.id%} </th>
</td>
<td>${{product.price}}</td>
</tr>
{% endfor %}
<tr>
<th colspan='2'></th>
<td> <b>Subtotal : $</b><span class="cart-subtotal">{{cart.subtotal}}</span> </td>
</tr>
<tr>
<th colspan='2'></th>
<td> Tax : $<span class="cart-tax" >{{cart.tax}} </span></td>
</tr>
<tr>
<th colspan='2'></th>
<td> <b>Total : $</b><span class="cart-total">{{cart.total}} </span> </td>
</tr>
<tr>
<th colspan='2'></th>
<td> <a class="btn btn-success" href="{% url 'carts:checkout' %}">Checkout</a> </td>
</tr>
</tbody>
</table>
<div class="cart-item-remove-form" style='display:none'>
{% include "carts/snippets/remove-product.html" with product_id=product.id%}
</div>
{% else %}
<p class="lead">There is no porduct in your cart now! </p>
<p> <a class="btn btn-secondary" href="{% url 'products:list' %}">Go to check!</a> </p>
{% endif %}
{% endblock content %}
views.py
def cart_detail_api_view(request):
cart_obj, new_obj = Cart.objects.new_or_get(request)
products = [{
"ud":x.id,
"url":x.get_absolute_url(),
"name":x.name,
"price":x.price,
}
for x in cart_obj.products.all()]
cart_data ={"products":products,"subtotal":cart_obj.subtotal,"total":cart_obj.total,"tax":cart_obj.tax()}
return JsonResponse(cart_data)
def cart_update(request):
product_id = request.POST.get('product_id')
if product_id:
try:
product_obj = Product.objects.get(id=product_id)
except Product.DoesNotExist:
print("Show message to user, product does not exist")
raise("Producr does not exist")
return redirect("carts:home")
else:
cart_obj, new_obj = Cart.objects.new_or_get(request)
if product_obj in cart_obj.products.all():
cart_obj.products.remove(product_obj)
product_added = False
else:
cart_obj.products.add(product_obj) # cart_obj.products.add(1)
product_added = True
request.session['cart_items'] = cart_obj.products.count()
if request.is_ajax(): #Asynchronous JavaScript Anx XML / JSON(JaveScrtip Object Notation)
print("Ajax request")
json_data = {
"productAdded":product_added,
"productRemoved":not product_added,
"cartItemCount":cart_obj.products.count()
}
return JsonResponse(json_data)
return redirect("carts:home")
Related
Good evening,
inside my page there are two areas - one in which the form with the new data is submitted and a second one where all the entries should be displayed inside a table..
I'm still new to javascript, so I'm asking myself, wether it's possible to update the table with the new data after pressing the submit button (and without refreshing the whole page)!?
models.py
class AjaxTable(models.Model):
first_name = models.CharField(max_length=25, null=False, blank=False)
last_name = models.CharField(max_length=25, null=False, blank=False)
age = models.IntegerField(default=0, validators=[MinValueValidator(1), MaxValueValidator(100)])
def __str__(self):
return f"{self.first_name} {self.last_name}"
views.py
def javascript_ajax_table_update(request):
qs_table = AjaxTable.objects.all()
form = AjaxTableForm()
data = {}
if request.is_ajax():
form = AjaxTableForm(request.POST, request.FILES)
if form.is_valid():
form.save()
data['first'] = form.cleaned_data.get('first_name')
data['last'] = form.cleaned_data.get('last_name')
data['age'] = form.cleaned_data.get('age')
data['status'] = 'ok'
return JsonResponse(data)
context = {'formset': form, 'qs_table': qs_table}
return render(request, 'app_django_javascript/create/django_javascript_ajax_table_update.html', context)
forms.py
class AjaxTableForm(ModelForm):
class Meta:
model = AjaxTable
fields = '__all__'
template.html
<div class="grid-container">
<div class="cnt-create">
<div class="card">
<div class="card-body">
<form action="" method="post" autocomplete="off" id="post-form" name="post-form">
{% csrf_token %}
<div class="div-post-input-flex">
<div class="div-post-input">
<label>First Name</label><br>
{{ formset.first_name }}
</div>
<div class="div-post-input">
<label>Last Name</label><br>
{{ formset.last_name }}
</div>
<div class="div-post-input">
<label>Age</label><br>
{{ formset.age }}
</div>
</div>
<div class="div-post-input">
<button class="btn btn-success" type="submit">
Save
</button>
</div>
</form>
</div>
</div>
</div>
<div class="cnt-view">
<div class="card">
<div class="card-body">
<table class="table table-hover" id="ajax-table">
<thead>
<tr>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Age</th>
</tr>
</thead>
<tbody>
{% for item in qs_table %}
<tr>
<td>{{ item.first_name }}</td>
<td>{{ item.last_name }}</td>
<td>{{ item.age }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
script
const form = document.getElementById('post-form')
const first_name = document.getElementById('id_first_name')
const last_name = document.getElementById('id_last_name')
const age = document.getElementById('id_age')
const csrf = document.getElementsByName('csrfmiddlewaretoken')
const url = ""
form.addEventListener('submit', e=>{
e.preventDefault()
const fd = new FormData()
fd.append('csrfmiddlewaretoken', csrf[0].value)
fd.append('first_name', first_name.value)
fd.append('last_name', last_name.value)
fd.append('age', age.value)
$.ajax({
type: 'POST',
url: url,
enctype: 'multipart/form-data',
data: fd,
success: function(response){
console.log(response)
setTimeout(()=>{
first_name.value = ""
last_name.value = ""
age.value = 0
}, 1000)
},
error: function(response){
console.log(response)
},
cache: false,
contentType: false,
processData: false,
})
})
I want to count the number of correct answers and display it.i tried many ways but couldn't go through.will appreciate if anybody can help me .Thanks in advance.
{% extends 'base.html' %}
{% block title%}Quiz{% endblock title %}
{% block content %}
<div class=" text-danger mt-5 text-center">
<!-- <h2><b id="count">Timer</b></h2> -->
<h3>+++Quiz on Indian Politics+++</h3>
<hr>
</div>
<div class="pt-5">
{% for item in obj %}
<table>
<tr>
<h2>Q{{item.id}}. {{item.question}}</h2><br>
</tr>
<tr>
<input type="radio" class="rd" name="{{item.id}}" id="opt1" value="{{item.opt1}}"> {{item.opt1}}</input><br>
</tr>
<tr>
<input type="radio" class="rd" name="{{item.id}}" id="opt2" value="{{item.op2}}"> {{item.opt2}}</input><br>
</tr>
<tr>
<input type="radio" class="rd" name="{{item.id}}" id="opt3" value="{{item.opt3}}"> {{item.opt3}}</input><br>
</tr>
<tr>
<input type="radio" class="rd" name="{{item.id}}" id="opt4" value="{{item.opt4}}"> {{item.opt4}}</input><br>
</tr>
<tr>
<label id="lb" class="rd" name="{{item.id}}" value="{{item.cor_ans}}" style='display:none;color:green'><b>The correct answer is: {{item.cor_ans}}</b></label>
</tr>
<tr>
</tr>
</table>
<hr> {% endfor %}
<div class="pt-4">
<button type="submit" class="btn btn-success" id="btn">Submit</button>
</div>
<div class="pt-3">
<b id="counter"></b>
<b id="ans"></b>
</div>
</div>
{% endblock content %}
{% block scripts %}
<script>
const rad = document.getElementsByClassName('rd')
const input = document.getElementsByTagName('input')
const bt = document.getElementById('btn')
const label = document.getElementsByTagName('label')
const counter = document.getElementById('counter')
var score = 0;
bt.onclick = function() {}
// JQuery code
$(document).ready(function() {
$('#btn').click(function() {
$('.rd').show();
$('.rd').attr("disabled", true);
});
});
// # javascript code
bt.addEventListener('click', function() {
for (i = 0; i < input.length; i++) {
if (input[i].type === 'radio') {
if (input[i].checked) {
document.getElementById('ans').innerHTML += "Q" + input[i].name + " The Answer you selected is: " + input[i].value + "<br>";
}
}
}
})
// var interval = setInterval(function(){
// document.getElementById('count').innerHTML=count;
// count--;
// if (count === 0){
// clearInterval(interval);
// document.getElementById('count').innerHTML='Done';
// alert("You're out of time!");
// }
// }, 1000);
// document.getElementsByClassName('counter').innerHTML = cnt;
// console.log(label[j].innerHTML.replace("<b>The correct answer is: ","").replace("</b>",""))
//
// if(label[j].innerHTML.replace("<b>The correct answer is: ","").replace("</b>","") == input[i].value){
// console.log("Hello")
// }
</script>
{% endblock scripts %}
I want to query the database and show the result don't refresh the page. So I use the Ajax! But when I append or paste the html code, the javascript isn't work. The style of my table is so ugly.
This is table html part that output will be here (ID=output) :
<div class='fresh-table' id="output">
<div class='toolbar'>
<button type='button' id='alertBtn' class='btn btn-info'>Add To Cart</button>
</div>
<table id='fresh-table' class='table'>
<thead>
<th data-field='state' data-checkbox='true'></th>
<th data-field='id' data-sortable='true'>id</th>
<th data-field='name' data-sortable='true'>candidate</th>
<th data-field='salary' data-sortable='true'>salary</th>
<th data-field='gpa' data-sortable='true'>gpa</th>
<th data-field='position'>position</th>
<th data-field='actions' class='td-actions text-right' data-formatter='operateFormatter' data-events='operateEvents'>Actions</th>
</thead>
<tbody>
{% for candidate in Candidate %}
<tr data-val='{{candidate.id_number}}'>
<td></td>
<td><a href='/filter/{{candidate.id_number}}/' style='color: #ff9800; font-weight: 400;'>{{candidate.id_number}}</a></td>
<td>{{ candidate.name_title }} {{candidate.firstname}}    {{candidate.lastname}}</td>
<td>{{candidate.salary}}</td>
<td>{{candidate.nowEdu_gpa}}</td>
<td>{{candidate.position}}</td>
<td></td>
</tr>
{% endfor%}
</tbody>
</table>
</div>
This is Ajax in template:
$.ajax({
type: 'POST',
url: 'testajax/',
dataType: "json",
async: true,
data: {
filter_option: json_filter_option,
operator_position: json_operator_position,
filter_position: json_filter_position,
csrfmiddlewaretoken: "{{ csrf_token }}"
},
success: function(json) {
console.log(json.message)
html = "<div class='toolbar'> <button type='button' id='alertBtn' class='btn btn-info'>Add To Cart</button></div><table id='fresh-table' class='table'><thead><th data-field='state' data-checkbox='true'></th><th data-field='id' data-sortable='true'>เลขประจำตัวประชาชน</th><th data-field='name' data-sortable='true'>ชื่อผู้สมัคร</th><th data-field='salary' data-sortable='true'>เงินเดือนที่คาดหวัง</th><th data-field='gpa' data-sortable='true'>เกรดเฉลี่ยสะสม</th><th data-field='position'>ตำแหน่งที่สมัคร</th><th data-field='actions' class='td-actions text-right' data-formatter='operateFormatter' data-events='operateEvents'>Actions</th></thead><tbody>";
$.each(json.message, function(index, candidate) {
html += "<tr data-val='" + candidate[0] + "'><td></td><td><a href='/filter/" + candidate[0] + "/' style='color: #ff9800; font-weight: 400;'>" + candidate[0] + "</a></td><td>{{ candidate.name_title }} {{candidate.firstname}}    {{candidate.lastname}}</td><td>{{candidate.salary}}</td><td>{{candidate.nowEdu_gpa}}</td><td>{{candidate.position}}</td><td></td></tr>";
});
html += "</tbody></table>";
$('#output').html(html);
}
})
Please help me. This project is so important for me.
The style of table that I use is from : https://www.creative-tim.com/product/fresh-bootstrap-table
This is my view.py
def test_ajax(request):
if request.method == 'POST':
print("Entryy")
filter_option = json.loads(request.POST.get('filter_option'))
operator_position = json.loads(request.POST.get('operator_position'))
filter_position = json.loads(request.POST.get('filter_position'))
print("filter_option",filter_option)
print("operator_position",operator_position)
print("filter_position",filter_position)
all_candidate = CandidateBasic.objects.all().values_list('id_number')
response_data = {}
try:
response_data['result'] = "Success"
response_data['message'] = list(all_candidate)
print(response_data)
except Exception as e:
response_data['result'] = "Fail"
response_data['message'] = "Fail!"
return HttpResponse(json.dumps(response_data), content_type="application/json")
This might just be a start, but in your AJAX $.each, you populate a lot of data but don't actually do anything with it. All you put into your page HTML is your html, which doesn't appear to have any view context in it. Maybe you want to consider using JsonResponse instead of HttpResponse
I have a Jquery/Ajax call which updates cart details. At the moment I can't get the existing HTML in the cart-body(tablebody) to clear. The actual ajax request works and all items are added to cart but the original HTML entries stay. The particular code is here:
if (data.products.length > 0 ) {
productRows.html("")
$(cartBody).empty()
Jquery Function
function refreshCart() {
console.log("in current cart")
var cartTable = $(".cart-table")
var cartBody = cartTable.find(".cart-body")
var productRows = cartBody.find(".cart-product")
var cartTotal = cartTable.find(".cart-total-sec")
var productQuantity = cartTable.find(".cart-item-quanity")
var currentUrl = window.location.href
var refreshCartUrl = '/api/cart/'
var refreshCartMethod = "GET";
var data = {};
$.ajax({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
success: function(data) {
console.log("success")
console.log(data)
if (data.products.length > 0 ) {
productRows.html("")
$(cartBody).empty()
$.each(data.products, function(index, value) {
console.log(value)
console.log(data.count)
cartBody.append("<tr><td>" + value.quantity + " x" + "</td><td>"+ value.name + "</td><td>" + "£" + value.price + "</td></tr>")
})
cartTotal.find(".cart-total").text(data.total)
console.log(data.total)
} else {
window.location.href = currentUrl
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
}
HTML Form:
<div>
<h4>This is your shopping cart</h4>
<table class="cart-table">
<tr>These are the items in your basket and their respective totals</tr><br>
<tbody class="cart-body">
{% for item in cart.items %}
<form method="POST" action='{% url "shopping-cart-remove" %}'>
{% csrf_token %}
<tr class="cart-product"><span class="cart-item-quanity">{{ item.quantity }}</span> x {{ item.product.name }} = {{ item.subtotal }}</tr>
<input type="hidden" name='id' value='{{ item.product.id }}'>
<span class='remove-span'><button>remove</button><br></span>
</form>
</tbody>
{% endfor %}
<tr class="cart-total-sec"><td class="cart-price">{{ cart.total }}</td></tr>
</div>
Any help is really appreciated.
First you are making mistake, as i can see there's form in table, on refreshing you will lose that form so i guess you should append items in form not in .cart-body.
And for emptying html use cartBody.html(""); and you don't have to use productRows.html("") at all.
The issue as pointed out by Ultrazz008, was that the HTML was incorrectly formatted. For reference:
<table class="cart-table">
<tbody class="cart-body">
<form method="POST" class='form-product-ajax' action='{% url "shopping-cart-remove" %}' data-endpoint='{% url "shopping-cart-remove" %}'>
{% csrf_token %} {% for item in cart.items %}
<tr class=cart-product>
<td>{{ item.quantity}} x {{ item.product.name }} {{ item.subtotal }}
<input type="hidden" name='id' value='{{ item.product.id }}'>
<button class='remove-btn'>remove</button>
</td>
{% endfor %}
</tr>
</form>
</tbody>
<tr class="cart-total-sec">
<td class="cart-price">{{ cart.total }}</td>
</tr>
</table>
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.