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

前端 未结 7 2056
执笔经年
执笔经年 2021-02-02 01:54

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

I have a search form that looks like this: \"searc

7条回答
  •  礼貌的吻别
    2021-02-02 02:16

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

    public static IQueryable DynamicWhere(this IQueryable 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>(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.

提交回复
热议问题