我有一个动作SearchPost。在获取行动中:
ViewBag.cities = db.cities.ToList();
ViewBag.areas = db.areas.ToList();
IEnumerable<SelectListItem> Months =pm.GetMyMonthList().Select(a => new
SelectListItem {
Value = a.Value,
Text = a.Text
}).ToList();
ViewBag.monthList = Months;
IEnumerable<SelectListItem> rentTypes = pm
.GetRentType()
.Select(a => new SelectListItem
{
Value = a.Value,
Text = a.Text
})
.ToList();
ViewBag.typeList = rentTypes;
return View(db.posts.Include("user").ToList());
视图页面中的
@Html.DropDownList("City",new SelectList(ViewBag.cities as
System.Collections.IEnumerable, "city_id", "name"),
"Select City", new { id = "ddlCars" })
@Html.DropDownList("Area", new SelectList(Enumerable.Empty<SelectListItem>(),
"area_id", "name"),
"Select Area", new { id = "ddlModels" })
@Html.DropDownList("rent_type", new SelectList(ViewBag.typeList as
System.Collections.IEnumerable, "Value", "Text"), "Select Category")
@Html.DropDownList("month", new SelectList(ViewBag.monthList as
System.Collections.IEnumerable, "Value", "Text"), "Select Month")
在我的邮政行动中:
IList<post> p = db.posts.Include("user").ToList();
string Area = Request.Form["Area"];
string City = Request.Form["City"];
if (City != "Select City" && City != null && City !="")
{
int c_id = Convert.ToInt32(City);
city c = db.cities.Single(s => s.city_id == c_id);
ci = c.name;
}
if (Area != "Select Area" && Area != null && Area !="")
{
int a_id = Convert.ToInt32(Area);
area a = db.areas.Single(x => x.area_id == a_id);
ar = a.name;
}
string rent_type = Request.Form["rent_type"];
string month = Request.Form["month"];
if (rent_type != null && rent_type != "")
{
if ((p != null) && (p.Any()))
{
p = p.Where(a => a.rent_type == rent_type).ToList();
}
}
if (month!= null && month != "")
{
if ((p != null) && (p.Any()))
{
p = p.Where(a => a.rent_month == month).ToList();
}
}
return View(p);
这里我首先从我的数据库中选择所有帖子。然后我想按城市,地区,月份和rent_type过滤它。城市和地区是级联下拉列表。当我选择城市和区域时,它会正确过滤记录。但如果我只选择城市就会出错:
序列中不包含任何元素:
area a = db.areas.Single(x =&gt; x.area_id == a_id);当我尝试仅过滤月份或者rent_type时,它没有过滤记录并且总是没有记录。
我应该改变哪部分代码来解决这两个问题......< / p>
提前感谢...