AndrewC10
AndrewC10

Reputation: 357

ASP.NET MVC Search Box Not Posting Back to Index

I have a basic MVC app that I am trying to implement some search functionality on. When I enter data and click "Search", the url updates as expected, but the index page still returns all of the results, not the filtered results. I have my code below and was wondering if someone would be able to point out why this is the case? I do not believe I need a separate Post method, according to what I have done in the past, but I may be wrong as I am still new. Thanks.

INDEX.CSHTML:

<p>
    @Html.ActionLink("Create New Employee", "Create")
</p>

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

CONTROLLER:

public ActionResult Index(string searchString)
{
    var person = from p in db.Person
                    select p;

    ViewBag.CurrentFilter = searchString;

    if (!String.IsNullOrEmpty(searchString))
    {
        person = person.Where(s => s.LastName.Contains(searchString));
                                //|| p.FirstName.Contains(searchString));
    }
    return View(db.Person.ToList());
}

URL Being returned when clicking Search:

http://localhost:9999/Person/Index?searchString=smith

Upvotes: 0

Views: 435

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

Because You are returning wrong result back to view which is dictating to returns all rows from Persons table and pass it to view,so change the last line from:

return View(db.Person.ToList());

to:

return View(person.ToList());

so that it returns the filtered result set to the view.

Upvotes: 2

Related Questions