如何实现在C#/ ASP.NET MVC搜索功能 [英] How to implement search functionality in C#/ASP.NET MVC

查看:222
本文介绍了如何实现在C#/ ASP.NET MVC搜索功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个ASP.NET MVC 3应用程序使用C#和剃刀。

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

我有一个看起来像这样的搜索方式:

I have a search form that looks like this:

在搜索表单中的以下工作方式:

The search form works in the following way:

  1. 在用户选择他们想搜索哪个属性。
  2. 在用户选择他们希望如何匹配搜索字符串(例如包含,起始为,结尾,等于等)。
  3. 在用户输入搜索词,点击搜索。

在下降直接相关的属性在我的ADO.NET实体框架模型类(并因此直接将表列)的首次下降的选择。

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).

搜索的用户,例如,当需要明确选择哪个属性和它匹配的方法的能力用户将明确搜索的过程数等于132所有的比赛。

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'.

我的第一种方法是使用动态的LINQ to构建一个来自哪里的搜索标准条款(的看我原来的问题)。但是我开始认为这是不是做的最好方法。

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.

我也希望不需要我到c的结果为每个属性+匹配条件的组合很难$ C $的解决方案。

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.

推荐答案

您可以建立EX pression树的地方使用predicate code。例如,

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);
}

使用它作为 Orders.DynamicWhere(搜索项,searchValue)。您可以添加一个参数来接受,如等于操作,大于等完成的功能。

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

另外,请查阅对防爆pression类得到一个想法。

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

这篇关于如何实现在C#/ ASP.NET MVC搜索功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆