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

前端 未结 7 2032
执笔经年
执笔经年 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, like this:

    public class ComboPredicate
    {
        public Func Func {get; set;}
        public string Name {get; set; }
    }
    

    Later, when you load the form:

    comboProperty.Datasource = myEntityObject.GetType().GetProperties()
    comboOperation.Datasource = new List
        {
            {
                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));
    

提交回复
热议问题