Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create Search box with highlighting found data – Blazor –

I am working on creating blazor page that display search box to search from list , i want the matching string not the whole word to be highlighted if it match the input in search box the result now is
<mark>ap</mark>
and here is the code :

@page "/test"
@using System.Linq

<input type="text" @bind-value="@searchTerm" @bind-value:event="oninput" placeholder="Search" />

<ul>
    @foreach (var item in filteredItems)
    {
        <li>@GetHighlightedText(item)</li>
    }
</ul>

@code {
    private string searchTerm = "";

    private List<string> items = new List<string> { "apple", "banana", "cherry", "date", "elderberry" };

    private List<string> filteredItems
    {
        get
        {
            if (string.IsNullOrWhiteSpace(searchTerm))
            {
                return items;
            }
            else
            {
                return items.Where(item => item.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)).ToList();
            }
        }
    }

    private string GetHighlightedText(string text)
    {
        if (string.IsNullOrWhiteSpace(searchTerm))
        {
            return text;
        }

        int index = text.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase);
        if (index < 0)
        {
            return text;
        }

        string before = text.Substring(0, index);
        string match = text.Substring(index, searchTerm.Length);
        string after = text.Substring(index + searchTerm.Length);

        return $"{before}<mark>{match}</mark>{after}";
    }
}
<style>
    mark {
        background-color: yellow;
        color: black;
    }
</style>

I try to change the browser or change mark tag but i still have the same problem.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

try changing :

<li>@GetHighlightedText(item)</li>

to :

<li> @((MarkupString)GetHighlightedText(item)) </li>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading