我正在寻找在我的应用程序中搜索Stockitems
的帮助。在主页视图中,有一个类别的下拉列表(靴子,袜子等(旁边是一个搜索框,我想用它来搜索所选类别中的所有项目。
数据库表的关系如下:
- Category > SubCategory > StockItems
DDL
是一个HTML.DropDownList
,它可以通过选定的类别回传递,并使用Controller
拾取了CC_5。然后,是否可以使用LINQ
将成为所选类别的一部分的stockitem
S返回到视图中?
通过以下尝试,我目前会得到:
对象引用未设置为对象的实例
类如下 -
public class Category
{
public int Id { get; set; }
[DisplayName("Category")]
public string Name { get; set; }
public string Description { get; set; }
public int SubCategoryID { get; set; }
public virtual IList<SubCategory> SubCategory { get; set; }
}
public class SubCategory
{
public int Id { get; set; }
public int Name { get; set; }
public int CategoryID { get; set; }
public Category Category { get; set; }
public virtual List<StockItem> Items { get; set; }
}
public class StockItem
{
public int Id { get; set; }
public string SKU { get; set; }
public long Barcode { get; set; }
public string Title { get; set; }
public string Brand { get; set; }
public string Colour { get; set; }
public int StockItemID { get; set; }
public SubCategory SubCategory { get; set; }
public string Size { get; set; }
public int Quantity { get; set; }
public decimal UnitCost { get; set; }
}
控制器当前具有以下索引 -
public ActionResult Index(string searchString)
ViewBag.CategoryID = new SelectList(_categoryRepo.getCategories(), "Name", "Name");
var strDDLValue = Request["CategoryID"];
if (!String.IsNullOrEmpty(strDDLValue)) items = items.Where(r => r.SubCategory.Category.Name.Equals(strDDLValue) && r.Title.Contains(searchString))
return View(item);
确定在末尾弄清楚了...最终控制器类如下 -
public ActionResult Index(string searchString)
{
ViewBag.CategoryID = new SelectList(_categoryRepo.getCategories(), "ID", "Name");
// ViewModel
var items = _stockRepo.getStock().Select(r => r.toStockVM());
// Search
if (!String.IsNullOrEmpty(searchString))
{
searchString = searchString.ToUpper();
items = items.Where(r =>
r.Title.ToUpper().Contains(searchString));
}
if (!String.IsNullOrEmpty(Request["CategoryID"]))
{
var strDDLValue = Convert.ToInt32(Request["CategoryID"]);
if (strDDLValue >= 1)
{
searchString = searchString.ToUpper();
items = items.Where(r => r.SubCateogory.CategoryID == strDDLValue && r.Title.ToUpper().Contains(searchString));
}
}
return View(items);
}
为您的评论加油。如果其他人遇到同样的问题,请详细说明任何事情。