我有一个IEnumerable View.this视图页面(cshtml)包含一个模型数据和一些form.it列出数据的所有数据。我想通过多个过滤器选项过滤这些数据,例如按城市,区域,楼层,道路过滤,没有e.t.c所有那些过滤器都在我的表格字段中。我的动作如下:
[HttpPost]
public ViewResult SearchPost()
{
var posts =db.posts.Include("user").ToList();
if (Request.Form["searchString"] != null)
{
posts = (from posts in db.posts where posts.area
==Request .Form["searchString"]).ToList();
}
if (Request.Form["searchString2"] != null)
{
posts = (from posts in db.posts where posts.city
==Request.Form["searchString2"]).ToList();
}
if (Request.Form["searchString3"] != null)
{
posts = (from posts in db.posts where posts.floor
==Request.Form["searchString3"]).ToList();
}
return View(posts);
}
[HttpPost]
public ViewResult SearchPost()
{
var posts =db.posts.Include("user").ToList();
if (Request.Form["searchString"] != null)
{
posts = (from posts in db.posts where posts.area
==Request .Form["searchString"]).ToList();
}
if (Request.Form["searchString2"] != null)
{
posts = (from posts in db.posts where posts.city
==Request.Form["searchString2"]).ToList();
}
if (Request.Form["searchString3"] != null)
{
posts = (from posts in db.posts where posts.floor
==Request.Form["searchString3"]).ToList();
}
return View(posts);
}
我的观看页面:
@using (Html.BeginForm()){
<p> Area: @Html.TextBox("SearchString")
<p> City: @Html.TextBox("SearchString2")
<p> Floor: @Html.TextBox("SearchString3")
<input type="submit" value="Filter" /></p>
}
>.....list of Model Data
我的所有过滤器选项都是可选的。可以选择一个或多个过滤器选项,或者可以不选择它们。它给出错误范围变量帖子我希望在每个if条件块中过滤我的结果集。可能吗 ???如果可能的话请给我一些想法.....提前致谢
答案 0 :(得分:0)
检查null&amp;&amp;&amp;运行查询之前的任何()结果。过滤器1和/或2可能会排除您的所有结果。
if (Request.Form["searchString"] != null)
{
if ((posts!=null) && (posts.Any()))
{
posts = (from posts in db.posts where posts.area
==Request .Form["searchString"]).ToList();
}
}
if (Request.Form["searchString2"] != null)
{
if ((posts!=null) && (posts.Any()))
{
posts = (from posts in db.posts where posts.area
==Request .Form["searchString2"]).ToList();
}
}
if (Request.Form["searchString3"] != null)
{
if ((posts!=null) && (posts.Any()))
{
posts = (from posts in db.posts where posts.area
==Request .Form["searchString3"]).ToList();
}
}