HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMinor

Search and filter in MVC3 Razor using Linq

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
linqsearchfilterusingandmvc3razor

Problem

This code works fine, but I just don't like all the if else. If I keep adding field to filter, it's going to get messy.

I am not using EF and cannot on this.

Controller code:

var books = bookRepository.GetDogs();    
if (!String.IsNullOrEmpty(searchString))
{

    if (!String.IsNullOrWhiteSpace(searchString) && searchGender != String.Empty && searchHand != String.Empty)
    {
        books = books.Where(b => b.Name.ToUpper().Contains(searchString.ToUpper())
                                 && b.Gender == searchGender && b.Handedness == searchHand);
    }
    else if (!String.IsNullOrWhiteSpace(searchGender) && searchString == String.Empty && searchHand == String.Empty)
    {
        books = books.Where(b => b.Gender == searchGender);
    }
    else if (String.IsNullOrWhiteSpace(searchGender) && searchString != String.Empty && searchHand == String.Empty)
    {
        books = books.Where(b => b.Name.ToUpper().Contains(searchString.ToUpper()));
    }
}

return View(books);


My view:

Find by Name : @Html.TextBox("searchString", ViewBag.CurrentFilter as string)

@Html.DropDownList("searchGender", new SelectList(ViewBag.BookNames), "-- Select All --")
@Html.DropDownList("searchHand", new SelectList(ViewBag.HandNames), "---Select All--")

Solution

Just put if, not else if so you can have a cumulative multi criteria search, and one condition in every if.

So every condition is easy to read, and if more than one criteria is filled, they will cumulate fine.

if (!String.IsNullOrWhiteSpace(searchString))
   books = books.Where(b => b.Name.ToUpper().Contains(searchString.ToUpper());       

if (!String.IsNullOrWhiteSpace(searchGender))
   books = books.Where(b => b.Gender == searchGender);

if (String.IsNullOrWhiteSpace(searchHand))
   books = books.Where(b => b.Handedness == searchHand);

Code Snippets

if (!String.IsNullOrWhiteSpace(searchString))
   books = books.Where(b => b.Name.ToUpper().Contains(searchString.ToUpper());       

if (!String.IsNullOrWhiteSpace(searchGender))
   books = books.Where(b => b.Gender == searchGender);

if (String.IsNullOrWhiteSpace(searchHand))
   books = books.Where(b => b.Handedness == searchHand);

Context

StackExchange Code Review Q#16275, answer score: 5

Revisions (0)

No revisions yet.