The aim of this article is demonstrate how to create a simple live search using JavaScript Ajax on the client side and .NET MVC for the server side. It should be simple enough for developers of any level to understand. I'll also assume that you have an existing .NET project ready so I can skip this setup phase.
Introduction
Howdy all. For anyone that followed me over from Blogger land welcome to the greener pastures of Dev.to 🎉🥳 , and anyone else who has stumbled on this article thanks for at least reading this far !
This is my first post on Dev.to so I'm sure there'll be some getting used to the markdown, so bear with me please and I hope you find this useful.
What We'll Build
So What IS Ajax?
Ajax was the son of King Telamon , strongest of the Achaeans and the generally known scourge of Troy.
Err Ok ?
Or maybe it could also be short for Asynchronous JavaScript and XML. It is not a programming language but a series of techniques using different web technologies. Ajax allows us to send and receive data asynchronously in the background without having to deal with pesky page reloading if we were otherwise searching via a form submit action .
TLDR: Ajax is pretty useful.
The HTML
The HTML we need is pretty simple - just an input and another Div container to hold the search results.
<input id="livesearchtags" name="livesearchtags" placeholder="Search" autocomplete="off" />
<div id="result" class="tag-results">
</div>
The Javascript
All we need is to add an onkeyup event to the input so we can detect when the user types, and then take the input value and send it to the server via Ajax. The search results will be returned to us and inserted into the result elements.
document.getElementById('livesearchtags').addEventListener('keyup', function (e) {
//Run LiveSearch on ever key up
LiveSearch()
});
function LiveSearch() {
//Get the input value
let value = document.getElementById('livesearchtags').value
$.ajax({
type: "POST",
// You can use the absolute url eg www.site.com/MyControllerName/LiveTagSearch or the relative path live below
url: "/MyControllerName/LiveTagSearch",
// Attach the value to a parameter called search
data: { search: value },
datatype: "html",
success: function (data) {
// Insert the returned search results html into the result element
$('#result').html(data);
}
});
}
The Back End
I've created my backend with .NET Framework, but .NET Core is pretty similar. Of course you can do this with tech you're comfortable win - eg. PHP.
You'll need to create a new Controller in your project ( we are following the MVC pattern after all ).
Within this controller we'll search our DB for any relevant Tags.
// Structure of the Tag that we'll be searching for
// This would be in the Model Folder
public class Tag
{
public int Id { get; set; }
public string Name { get; set; }
}
// MyControllerName.cs Controller
public <ActionResult> LiveTagSearch(string search)
{
// Call your method to search your data source here.
// I'll use entity framework to query my DB
List<Tags> res = (
from t in _context.Tags
where t.Name.Contains(search)
select t
).ToList();
// Pass the List of results to a Partial View
return PartialView(res );
}
Now we need to create a Partial View for the controller. This will be the HTML that is returned back to the Client. Create a new View folder if it doesn't already exist called MyControllerName, and within this a new partial view called LiveTagSearch to match the name of the Action method.
Within the Partial View we'll use a foreach
loop to iterate over the List of results to create the html to return.
@using _sampleproject.models;
@model List<Tags>
@foreach (var item in Model)
{
<div class="search-tag" id="@item.Id" >
<div class="search-tag-detail">@item.Name
<span class="search-tag-close" >
<i class="fa fa-times "></i>
</span>
</div>
</div>
}
Ok . Great. This works fine.
There's just one small problem . It runs on every keyup
.
But that's what we want right ? Ideally no, its a bit of an overkill- we don't want to hit our server with a request for every letter added or removed. The user will likely type a few letters before pausing , and that's the point when we should run the search , not on each and every keyup
. We can achieve this with only a minor edit.
JavaSript Redux
We need to add a timeout within the keyup
event which will be cleared if the user types another letter.
// New timeout variable
let timeout = null;
document.getElementById('livesearchtags').addEventListener('keyup', function (e) {
// Clear existing timeout
clearTimeout(timeout);
// Reset the timeout to start again
timeout = setTimeout(function () {
LiveSearch()
}, 800);
});
Adding Style
Now that the feature is all but done we can add some style to get the results to display nicely.
I've decided because these are "tag labels" they need to be displayed as such , but you can change it to whatever you want.
.search-tag-detail{
display: flex;
flex-direction: row;
padding: 3px;
background-color: #d9edf7;
border-radius: 3px;
}
.search-tag{
display:flex;
margin:2px 2px 2px 0px;
}
.tag-results{
display: flex;
flex-direction: row;
}
Journeys End
That's it, if you've followed along you should have a Live Search feature using Ajax and .NET.
Thanks for reading ! 🥂
And if you're feeling generous you can buy me a coffee with the link below ( and yes its all for coffee, I drink a copius amount of it while writing ☕ )
Top comments (1)
Created an account Just to say thanks a lot for this :P