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

前端 未结 7 2053
执笔经年
执笔经年 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:25

    You can use Dynamic Linq and you can create the Where clausole with a utility class like this:

    public class Criteria 
    {
       StringBuilder sb = new StringBuilder();
       bool first = true;
    
       public void And(string property, string dbOperator, string value) {
           if (first)
           {
               sb.Append(" ").Append(property).Append(" ");
               sb.Append(" ").Append(dbOperator).Append(" ");
               sb.Append(" ").Append(value).Append(" ");
               first = false;
           }
           else
           {
               sb.Append(" && ").Append(property).Append(" ");
               sb.Append(" ").Append(dbOperator).Append(" ");
               sb.Append(" ").Append(value).Append(" ");
           }
       }
    
       public void Or(string property, string dbOperator, string value)
       {
           if (first)
           {
               sb.Append(" ").Append(property).Append(" ");
               sb.Append(" ").Append(dbOperator).Append(" ");
               sb.Append(" ").Append(value).Append(" ");
               first = false;
           }
           else
           {
               sb.Append(" || ").Append(property).Append(" ");
               sb.Append(" ").Append(dbOperator).Append(" ");
               sb.Append(" ").Append(value).Append(" ");
           }
       }
    
       public string ToString() 
       {
           return sb.ToString();
       }
    
    }
    

    So you can build a Criteria with many properties using Or or And methods and put it in the Where operator of Dynamic Linq.

提交回复
热议问题