Implement Like search with Entity Framework in ASP.Net Core MVC

Last Reply one month ago By dharmendr

Posted one month ago

Greetings sir, please I need your help. 

I have some values on my db like Orange is good, mango is good, orange is a fruit, paw paw is good

I want to iterate and return all the rows with orange with like or contain

Thanks sir

Posted one month ago

Hi Destinykid,

Using below article i have created the example.

ASP.Net Core: Simple Entity Framework Tutorial with example

You need to use Contains method in where clause.

Check this example. Now please take its reference and correct your code.

Controller

public class HomeController : Controller
{
    private DBCtx Context { get; }
    public HomeController(DBCtx _context)
    {
        this.Context = _context;
    }

    public IActionResult Index()
    {
        List<Customer> customers = this.Context.Customers.Take(10).ToList();
        return View(customers);
    }

    [HttpPost]
    public IActionResult Index(string name)
    {
        List<Customer> customers = this.Context.Customers.Where(x => x.ContactName.Contains(name)).ToList();
        return View(customers);
    }
}

View

@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@using EF_Core_MVC.Models;
@model IEnumerable<Customer>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form asp-controller="Home" asp-action="Index" method="post">
        <input type="text" name="name" />
        <input type="submit" value="Submit" />
    </form>
    <hr />
    <table cellpadding="0" cellspacing="0">
        <tr>
            <th>CustomerID</th>
            <th>ContactName</th>
            <th>City</th>
            <th>Country</th>
        </tr>
        @foreach (Customer customer in Model)
        {
            <tr>
                <td>@customer.CustomerID</td>
                <td>@customer.ContactName</td>
                <td>@customer.City</td>
                <td>@customer.Country</td>
            </tr>
        }
    </table>
</body>
</html>

Screenshot