开发者

Dynamic search option in MVC 1.0

I'm looking for a dynamic way to implement search in my MVC 1.0 application.

Let's say that I have a user c开发者_如何学Pythonontrol containing a textbox, a dropdown and a button. The user will put a query in the textbox, select the column from which to search in the dropdown and then press the search button.

On doing the above activity I want to do this in the model:

context.MyViewOrTableName.Where(p => (p.ColumnNameFromTheDropdown.Contains(DataFromTheTextbox)));

Whether the above scenario is possible in MVC 1.0 and if so then how? Any help would be appreciated.

Solution:

context.MyViewOrTableName.Where("" + ColumnNameFromTheDropdown + ".Contains(@0)", DataFromTheTextbox);

This happened only after including the namespace System.Linq.Dynamic created by Scott and referred by Omar in the post below.


I'm currently doing a similar thing.

That is, I have an MVC View which contains various search options (checkbox, dropdown, textbox), and I wanted an elegant way to return "search results".

So I created a simple class - e.g "ProductSearchCriteria".

This class contains nothing but getters/setters for the different search options (which I populate when the form is submitted via model binding).

I then accept this type as a parameter on my BLL method:

public ICollection<Product> FindProductsForCriteria(ProductSearchCriteria criteria)
{
   return _repository // GenericRepository<Product>
      .Find() // IQueryable<Product>
      .WithSearchCriteria(criteria) // IQueryable<Product>
      .ToList(); // List<Product>
}

As to how to apply the filters, well that depends on a few things. Firstly, I don't know if your using Linq-To-Sql, NHibernate, Entity-Framework, etc. Also it depends on your architecture (repository).

You're not going to be able to "dynamically" apply filters via lambda expressions (not easily, anyway).

What I did was create an extension method to gracefully apply the filters:

public static IQueryable<Product> WithSearchCriteria(this IQueryable<Product> source, ProductSearchCriteria criteria)
{
    var query = source;

   if (criteria.SearchFilterOne != null)
       query = query.Where(x => x.FieldInModel == criteria.SearchFilterOne);
   // inspect other criteria
}

As I said, it depends on your architecture and ORM. I use Entity Framework 4.0, which supports deferred execution, meaning I can build up queries on my objects (IQueryable), and apply filters before executing the query.


What you're looking for is a way to build dynamic LINQ queries. You can search for some details about it and the options out there, however, I believe that the Dynamic Linq library that Scott Guthrie wrote is exactly what you're looking for.

It lets you build queries from strings:

var query =
    db.Customers.
    Where("City = @0 and Orders.Count >= @1", "London", 10).
    OrderBy("CompanyName").
    Select("new(CompanyName as Name, Phone)");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜