6

我的模块中有两个下拉列表。

在一个下拉列表中,我硬编码了所有的运算符,例如<,>,<=,>=,==

在第二个下拉列表中,我硬编码了员工的薪水,例如1000,2000,3000,4000....50000

现在,如果我<从一个列表和2000第二个列表中选择并单击提交按钮,我应该得到工资低于 2000 的员工列表。

我想在 asp.net mvc3 中执行此操作

我怎样才能完成这项任务?我需要为此编写一个存储过程吗?

我创建了下拉列表,例如:

viewModel.OperatorsList = new[]
{
  new SelectListItem { Value = "<", Text = "<" },
  new SelectListItem { Value = ">", Text = ">" },  
  new SelectListItem { Value = "<=", Text = "<=" },
  new SelectListItem { Value = ">=", Text = ">=" },
  new SelectListItem { Value = "==", Text = "==" }
};

viewModel.SalaryList = new[]
{
  new SelectListItem { Value = "1000", Text = "1000" },
  new SelectListItem { Value = "2000", Text = "2000" },  
  new SelectListItem { Value = "3000", Text = "3000" },

  // and so on
};

我用它在视图中显示下拉列表:

<%: Html.DropDownListFor(x => x.Operators, Model.OperatorsList)%>
4

1 回答 1

6

好吧,你可以做这样的事情

假设viewModel是...您的viewModel,并且您有一个Employee具有属性的实体Salaryint在此示例中,它可能是decimal现实世界中的)

创建一个静态助手类

public static class MyHelper
    {
        // a dictionary for your operators and corresponding ExpressionType
        public static Dictionary<string, ExpressionType> ExpressionTypeDictionary = new Dictionary<string, ExpressionType>
        {
            {"<", ExpressionType.LessThan},
            {">", ExpressionType.GreaterThan},
            {">=", ExpressionType.GreaterThanOrEqual}
            //etc
        };
        //a method to filter your queryable
        public static IQueryable<Employee> FilterSalary(this IQueryable<Employee> queryable, int salary, string operatorType)
        {
            //left part of the expression : m
            var parameter = Expression.Parameter(typeof(Employee), "m");
            //body is the right part of the expression : m
            Expression body = parameter;
            //m.Salary
            body = Expression.Property(body, "Salary");
            //m.Salary <= 1000 (for example)
            body = Expression.MakeBinary(ExpressionTypeDictionary[operatorType], body, Expression.Constant(salary));
            //m => m.Salary <=1000
            var lambda = Expression.Lambda<Func<Employee, bool>>(body, new[] { parameter });
            //so it will be queryable.Where(m => m.Salary <= 1000)
            return queryable.Where(lambda);
        }
}

用法

var queryable = context.All<Employee>();//or something like that, returning an IQueryable<Employee>
queryable = queryable.FilterSalary(viewModel.Salary, viewModel.Operators);
于 2013-05-14T13:46:15.457 回答