Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement search functionality in C#/ASP.NET MVC

I am developing an ASP.NET MVC 3 application using C# and Razor.

I have a search form that looks like this: searchform

The search form works in the following way:

  1. The user selects which property they want to search on.
  2. The user selects how they want to match the search string (e.g. contains, starts with, ends with, equals, etc).
  3. The user enters a search term and clicks Search.

The selections in the first drop down related directly to a property in my ADO.NET Entity Framework model class (and therefore directly to a table column).

Users need the ability to explicitly select which property and which matching method when searching, e.g. a user will explicitly search for all matches of process number that equals '132'.

My first approach was to use dynamic linq to construct a Where clause from the search criteria (see my original question). However I'm starting to think that this isn't the best way to do it.

I'm also hoping for a solution that doesn't require me to hard code the result for each property + matching criteria combination.

Any suggestions on how I should implement this search? It doesn't have to be using my current search form, totally open to any other ideas that fit the requirements.

like image 788
dnatoli Avatar asked Aug 29 '11 00:08

dnatoli


2 Answers

Have you looked into using Lucene.NET for this project? given the nature of your searches it would be very simple to build that using Lucene, as it allows you to combine filters on different columns just like your requirements

like image 200
BlackTigerX Avatar answered Oct 06 '22 18:10

BlackTigerX


You can build expression tree for where predicate using code. For example,

public static IQueryable<T> DynamicWhere<T>(this IQueryable<T> src, string propertyName, string value)
{
    var pe = Expression.Parameter(typeof(T), "t");
    var left = Expression.Property(pe, typeof(T).GetProperty(propertyName));
    var right = Expression.Constant(value);
    // Illustrated a equality condition but you can put a switch based on some parameter
    // to have different operators
    var condition = Expression.Equal(left, right);

    var predicate = Expression.Lambda<Func<T, bool>>(condition, pe);
    return src.Where(predicate);
}

Use it as Orders.DynamicWhere(searchBy, searchValue). You can add one more parameter to accept the operator such as Equals, Greater Than etc to complete the function.

See these links for more info:

http://msdn.microsoft.com/en-us/library/bb882637.aspx

http://msdn.microsoft.com/en-us/library/bb397951.aspx

Also check list of methods on the Expression class to get an idea.

like image 42
VinayC Avatar answered Oct 06 '22 16:10

VinayC