11 July 2017

Filtering a List of Results in ASP.NET MVC 5

Here's a simple example on how to filter results based on the given name:


Controller

public ActionResult Index(string searchValue)
{          
    var emp = db.Profiles.Select(y => y);
    if (!String.IsNullOrEmpty(searchValue))
    {
        emp = emp.Where(y => y.Name.Contains(searchValue));
    }      
    return View(emp);

}


View

@using (Html.BeginForm())
{
    <p>
        Search by name: @Html.TextBox("SearchValue")
        <input type="submit" value="Search" />
    </p>
}

<table class="table">
    <tr>
         <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Age)
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Age)
        </td>      
    </tr>
}
</table>

No comments:

Post a Comment