我的模块中有两个下拉列表。
在一个下拉列表中,我对所有运算符进行了硬编码,例如<,>,<=,>=,==
在第二个下拉列表中,我有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)%>
答案 0 :(得分:6)
假设viewModel
是... viewModel
,并且您在此示例中有一个实体Employee
,其中包含属性Salary
(int
,它可能是现实世界中的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);