我的模块中有两个下拉列表.
在一个下拉列表中,我对所有运算符进行了硬编码,例如<,>,< =,> =,==
在第二个下拉列表中,我有员工的硬编码,如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)%>
解决方法
好吧,你可以做那样的事情
假设viewmodel是…你的viewmodel,并且你有一个具有属性Salary的实体Employee(此示例中为int,它在现实世界中可能是小数)
创建一个静态助手类
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);