Did everything, searched everywhere, thought everytime but now
Tried my best but still can’t handle it. Now running into a problem with a form submit to push data search to controller with javascript code.
I am not getting any error for the JavaScript when attempting to debug in browser. Can someone with more experience with JavaScript show me a better way with the given code?
Here is my code:
Controller:
public IActionResult FindProduct(string keyword)
{
List<Product> ls = new List<Product>();
if (string.IsNullOrEmpty(keyword) || keyword.Length < 1)
{
return PartialView("ListProductSearchPartial", null);
}
ls = _context.Products
.AsNoTracking()
.Include(a => a.Cat)
.Where(x => x.ProductName.Contains(keyword))
.OrderByDescending(x => x.ProductName)
.Take(10)
.ToList();
if (ls == null)
{
return PartialView("ListProductSearchPartial", null);
}
else
{
return PartialView("ListProductSearchPartial", ls);
}
}
Form Search in View index:
<form id="formSearch" class="header-searchbox">
<select class="nice-select select-search-category wide">
<option value="all">All Category</option>
<option value="product-item">Product Item</option>
<option value="product-item-2">Product Item 02</option>
<option value="product-item-3">Product Item 03</option>
<option value="product-item-4">Product Item 04</option>
<option value="product-item-5">Product Item 05</option>
</select>
<input id="keyword" class="input-field" type="text" placeholder="Enter Products">
<button id="btnSearch" class="btn btn-outline-whisper btn-primary-hover" type="submit"><i class="pe-7s-search"></i></button>
</form>
Javascript in View index:
@section Scripts {
<script>
$(document).ready(function () {
var formSP = document.getElementById("formSearch");
formSP.addEventListener("submit", (e) => {
$.ajax({
url: '@Url.Action("FindProduct", "Search")',
datatype: "json",
type: "POST",
data: { keyword: $('#keyword').val() },
async: true,
success: function (results) {
$('#records_table').html("");
$('#records_table').html(results);
},
error: function (xhr) {
alert('error');
}
});
});
});
</script>
}