Reputation:
<input type="search" list="txtSearch" @bind-value="@searchTerm" @onkeydown="@Enter">
<datalist id="txtSearch">
@foreach (var item in objText)
{
<option>@item.A</option>
<option>@item.B</option>
<option>@item.C</option>
<option>@item.D</option>
}
</datalist>
The default result is all items from SQL Server.
I want to introduce the first 50
And that the normal behavior (only) when typing shows everything blazor of course
Upvotes: 0
Views: 1084
Reputation: 38
Datalist isn't ideal element for this because if someone start to browse available options from list there will be only 50 of them, not containing every option. Also typing would require constant rerefeshing of available options.
If you still want to use it that way, though, you should filter your data from SQL Server by using
var filteredObjText = objText.GetRange(0, 50);
Then use filteredObjText
in @foreach
. In Enter
method there should be filtering data by using something like
filteredObjText = objText
.Where(q => q.A.Contains(searchTerm) ||
q.B.Contains(searchTerm) ||
q.C.Contains(searchTerm) ||
q.D.Contains(searchTerm))
.GetRange(0, 50);
StateHasChanged();
Resulting code would also be different if you want to list only 50 properties or only properties matching typed filter.
Here is full working code for this (with some fixes of problems overlooked in my original answer).
@page "/"
<input type="search" list="txtSearch" @bind-value="@searchTerm" @onkeydown="@Enter">
<datalist id="txtSearch">
@foreach (var item in filteredObjText)
{
<option>@item.A</option>
<option>@item.B</option>
<option>@item.C</option>
<option>@item.D</option>
}
</datalist>
@code{
private string searchTerm { get; set; }
private List<Item> objText { get; set; } = new List<Item>();
private List<Item> filteredObjText { get; set; } = new List<Item>();
private void Enter()
{
if (!string.IsNullOrEmpty(searchTerm))
{
filteredObjText = objText
.Where(q => q.A.Contains(searchTerm) ||
q.B.Contains(searchTerm) ||
q.C.Contains(searchTerm) ||
q.D.Contains(searchTerm))
.ToList();
if (filteredObjText.Count > 50)
{
filteredObjText = filteredObjText.GetRange(0, 50);
}
StateHasChanged();
}
}
protected override void OnInitialized()
{
//get data from SQL Server
int i = 1;
for(int j = 0; j < 100; j++)
{
objText.Add(new Item() { A = (i++).ToString(), B = (i++).ToString(), C = (i++).ToString(), D = (i++).ToString()});
}
filteredObjText = objText.GetRange(0,50);
}
public class Item
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
public string D { get; set; }
}
}
It's worth noting that browsers capture alphanumeric input so to really fire Enter() there is need to press some combination of tab, shift, enter or one of arrow keys.
Upvotes: 1