GG6565
GG6565

Reputation: 138

How to search by string

My website can show the data now. I want add a function which can search string with Primary key. How do I create a search option for my website? Can sb send the teaching paper for me? I have read it. but I still have no idea. https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page?view=aspnetcore-5.0. and also I have try this way. But I do not know why my "contain" can't use.

    public async Task<IActionResult> Index(string searchString)
{
    var movies = from m in _context.Movie
                 select m;

    if (!String.IsNullOrEmpty(searchString))
    {
        movies = movies.Where(s => s.Title.Contains(searchString));
    }

    return View(await movies.ToListAsync());
}

Upvotes: 0

Views: 93

Answers (1)

Zhi Lv
Zhi Lv

Reputation: 21526

You can check the following code:

In the Index View Page: submit the form to the Index Action via the Get method, and for the search text box, named as searchString. For the Search button, use the submit type:

<form asp-action="Index" method="get">
    <div class="form-actions no-color">
        <p>
            Find by name: <input type="text" name="searchString" value="@ViewData["CurrentFilter"]" />
            <input type="submit" value="Search" class="btn btn-default" /> |
            <a asp-action="Index">Back to Full List</a>
        </p>
    </div>
</form>

Then, in the Index action method, you can add break point to check whether the parameter value is correct or not, and check the query result.

the screenshot as below:

enter image description here

More detail information, you can check the tutorial and the sample code.

Upvotes: 1

Related Questions