Autocomplete , or word completion, is a feature in which an application predicts the rest of a word a user is typing.
Create View Components
View components are similar to partial views, but they're much more powerful.
View components don't use model binding, and only depend on the data provided when calling into it.
public class AutocompleteViewComponent : ViewComponent
{
private readonly IProductRepository repository;
public AutocompleteViewComponent(IProductRepository repo)
{
repository = repo;
}
public IViewComponentResult Invoke()
{
ViewBag.SelectedName = RouteData?.Values["name"];
var n =(repository.GetProducts
.Select(x => x.Name)
.Distinct()
.OrderBy(x => x));
var c = (repository.GetProducts
.Select(x => x.Category)
.Distinct()
.OrderBy(x => x));
var items = n.Concat(c);
return View(items);
}
}
Create name of products C# array use View Component
View component classes can be contained in any folder in the project.
Because the class name AutocompleteViewComponent ends with the suffix ViewComponent,
the runtime will use the string "Autocomplete" when referencing the class component from a view.
@{
string word = "";
using (var writer = new System.IO.StringWriter())
{
(await Component.InvokeAsync("Autocomplete")).WriteTo(writer, HtmlEncoder);
word = writer.ToString();
}
var plaintext = GreensMan.Utils.HtmlUtils.HtmlToPlainText(word);
var words = plaintext.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
Convert C# array to JavaScript
//convert C# array to javascript arra
var arr = new Array();
var arra = new Array();
var sentence = "";
window.onload = function () {
var array = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(words));
var i;
for (i = 0; i < array.length; i++) {
arr.push(array[i]);
}
}
Create JavaScript Function "Autocomplete"
The autocomplete function takes two arguments, the text field element and array of name of producnts.
Check if name of productns from array start from the argument from the text field element, and than repeat.