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

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

    You could have the first combo data source set to myEntityObject.GetType().GetProperties(), the second to a list of displayable Funcs<string, string, bool>, like this:

    public class ComboPredicate
    {
        public Func<string, string, bool> Func {get; set;}
        public string Name {get; set; }
    }
    

    Later, when you load the form:

    comboProperty.Datasource = myEntityObject.GetType().GetProperties()
    comboOperation.Datasource = new List<Predicate>
        {
            {
                Name = "Contains",
                Predicate = (s1, s2) => s1 != null && s1.Contains(s2),
            },
            {
                Name = "Equals",
                Predicate = (s1, s2) => string.Compare(s1, s2) == 0,
            },
            //...
        }
    

    And later, when you want to select your entities:

    var propertyInfo = (PropertyInfo)comboProperty.SelectedValue;
    var predicate = ((ComboPredicate)comboOperation.SelectedValue).Predicate;
    var filteredObjects = objects.Where(o => predicate(propertyInfo.GetValue(o, null).ToString(), textBoxValue.Text));
    
    0 讨论(0)
提交回复
热议问题