Home > Blockchain >  Asp.Net Core 3.1-Search for a phrase and suggest 5 similar phrases with Ajax?
Asp.Net Core 3.1-Search for a phrase and suggest 5 similar phrases with Ajax?

Time:09-27

I have a search Input box and I want display 5 similar phrases every time a user searches for a phrase?

for Example : If the user searched for "ram" ... Return the following word system to me and display it ram 4 ram 8 ram 16 rampal ...

What the best way would you suggest?

CodePudding user response:

for the search use efcore and linq .Like(c.Name, "a%").take(5) or .contains("a").take(5) and for working with ajax build an api that it's get the search word and return the json list and show it with ajax just search "show json list item with ajax in asp.net core"

CodePudding user response:

I suggest you can use Autocomplete plugin in jQuery UI. Here is a simple demo you could follow:

Model:

public class Test
{
   public int Id { get; set; }
   public string Name { get; set; }
}

View(Index.cshtml):

<input type="text" id="tags" />
@section Scripts{
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
        $(function () {            
            $("#tags").autocomplete({
                source: '/Home/Test'                  
            });
        });
    </script>
}

Controller:

public class HomeController : Controller
{
    private readonly YourDbContext _context;

    public HomeController(YourDbContext context)
    {
        _context = context;
    }    
    [HttpGet]
    public IActionResult Index()
    {
        return View();
    }
    [HttpGet]
    public IActionResult Test()
    {
        var name = HttpContext.Request.Query["term"].ToString();
        var testname = _context.Tests.Where(c => c.Name.Contains(name))
                                    .OrderBy(a=>a.Name)
                                    .Select(c => c.Name)
                                    .Take(5)
                                    .ToList();
        return Ok(testname);
    }
}

Reference:

https://jqueryui.com/autocomplete/

  • Related