I'm using MVC 5, C# and I'm trying to build a search filter that will filter through upon each key stroke. It works as so, but the textbox erases after submitting. Now this is probably not the best approach to it either. Is there a way to make so when it posts it doesn't erase the textbox, or better yet, is there a better alternative?
@using (Html.BeginForm("Index", "Directory", FormMethod.Post, new { id = "form" }))
{
<p>
Search Employee: <input type="text" name="userName" onkeyup="filterTerm(this.value);" />
</p>
}
<script>
function filterTerm(value) {
$("#form").submit();
event.preventDefault();
}
</script>
A better way is to ditch your
Html.BeginForm
(unless you actually need it for something else) and use a pure ajax method of getting the data.So your modified html would be:
You also need to change the action that ajax will be calling (and I have no idea why you are calling the "Index" action).
The best thing about this ajax is there is no posting and it's async, so you don't have to worry about losing your data.
I agree with the comments on your question. Posting on every key stroke would be a frustrating user experience.
So, two answers, use ajax to perform the search (which will then keep the value since the whole page will not post) or have a submit button and name the input the same as the controller action parameter.
Controller code (used with your existing code):
View Code (to replace your code with Ajax):