Search code examples
asp.net-coreasp.net-core-mvcsearchbar

Send view with sorted items and query parameters (Search Bar) in Asp .Net Core 3.1


I created a search bar like this

 <form method="post" asp-action="Search">
    <input type="text" name="search" placeholder="Enter here the Name " />
    <select name="type" id="type" class="form-control">
        <option value="Success">Inactive Reservation</option>
        <option value="Approved">Active Reservation</option>
        <option value="Pending">Pending Reservation</option>
    </select>
    <input type="submit" value="Search" />
</form>

and the method in controller:

public async Task<IActionResult> Search(string search,string type)      
{       
    var allRsv = from m in _db.Reservation
                 select m;

    var Rsv = allRsv
        .Where(x => x.ClientName.ToLower().Contains(search.ToLower()) && 
                    x.Status.ToLower().Contains(type.ToLower()));

    return View(Rsv);
}

What I want: to send in search page something like 'You searched for @search and type: @type.

return View has no option to do this ,neither return to action ..

Can I do it in a simple way ?

My single idea it is to send query string and then request query in search view


Solution

  • What I want: to send in search page something like 'You searched for @search and type: @type.

    You can try to pass data to search page via ViewData etc, like below.

    In View Page

    <form method="post" asp-action="Search">
        <input type="text" name="search" placeholder="Enter here the Name " />
        <select name="type" id="type" class="form-control">
            <option value="Success">Inactive Reservation</option>
            <option value="Approved">Active Reservation</option>
            <option value="Pending">Pending Reservation</option>
        </select>
        <input type="submit" value="Search" />
    </form>
    
    <h3>You searched for "@ViewData["search"]" and type: @ViewData["type"].</h3>
    

    In Action Method

    public async Task<IActionResult> Search(string search, string type)
    {
        var allRsv = from m in _db.Reservation
                        select m;
    
        var Rsv = allRsv
            .Where(x => x.ClientName.ToLower().Contains(search.ToLower()) &&
                        x.Status.ToLower().Contains(type.ToLower()));
    
        ViewData["search"] = search;
        ViewData["type"] = type;
    
        return View(Rsv);
    }
    

    Test Result

    enter image description here