我是MVC的新手,任何帮助将不胜感激。我目前有一个显示数据表的页面。我想添加一个按钮,当单击该按钮时,会将一个附加过滤器添加到页面,如果再次单击将清除过滤器(切换功能)。
下面是我要使用的代码的预览。我相信该视图将满足我的需求,但是我不确定控制器。
查看按钮:
<td width="15%">
@if (ViewBag.curStatus == "NotFiltered")
{
@Html.ActionLink("Filter", "Index", new
{
sortOrder = ViewBag.CurrentSort,
qryStatus = ""
}, new { @class = "btn btn-primary btn-xs" })
}
else
{
@Html.ActionLink("Filter", "Index", new
{
sortOrder = ViewBag.CurrentSort,
qryStatus = "Filtered"
}, new { @class = "btn btn-default btn-xs" })
}
</td>
控制器:
public ActionResult Table(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ?
"invlocation" : "";
ViewBag.curStatus = String.IsNullOrEmpty(sortOrder) ?
"NotFiltered" : "Filtered";
var samples = from s in db.Table1
select s;
switch (sortOrder)
{
case "NotFiltered":
string selectqry = "select * from Table1 where datereceived is null ";
selectqry = selectqry + " and submissionid not in (select id from Table2 where status='Done')";
break;
case "Filtered":
selectqry = selectqry + " and status <> 'Pending'";
break;
}
List<vFiltered> list = db.Table1.SqlQuery(selectqry).ToList();
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(vFiltered.ToPagedList(pageNumber, pageSize));
}
答案 0 :(得分:0)
我要提到的第一件事是,您的MVC模式有些松散,并且控制器中的代码比我选择的要多得多。
我和IMO最好的方法是将逻辑转移到业务层或存储库中。
在存储库中/查询:
string selectqry = "select * from Table1 where datereceived is null ";
总是发生,因此它应该在if / case语句之外。
如果您不使用Entity Framework,并且想要手动构建查询,则可以执行以下操作:
switch (sortOrder)
{
case "NotFiltered":
selectqry = selectqry + " and submissionid not in (select id from Table2 where status='Done')";
break;
case "Filtered":
selectqry = selectqry + " and status <> 'Pending'";
break;
}
或更干净一点:
Dictionary<string, string> filters = new Dictionary<string, string>()
{
{"NotFiltered", "and submissionid not in (select id from Table2 where status='Done')"},
{"Filtered", " and status <> 'Pending'"}
}
然后:
string selectqry = "select * from Table1 where datereceived is null ";
selectqry += filters[sortOrder];
尽管如此,为什么过滤器称为排序顺序?
更好的是,我完全放弃了sql字符串,并设置了dbContext(假设实体框架),并做了更多类似的事情:
var results = dbContext.Table1;
if (sortOrder == "NotFiltered")
{
results.where(x => !dbContext.Table2.Select(s => s.Id).Contains(x.Id);
}
else
{
results.where(x => x.Status != "Pending");
}
return results.ToList();