通过类别DropDownList ASP.NET MVC搜索

时间:2018-02-14 20:15:11

标签: c# asp.net-mvc entity-framework

我正在寻找在我的应用程序中搜索Stockitems的帮助。在主视图中有一个下拉列表的类别(靴子,袜子等..)旁边是一个搜索框,我想用它来搜索所选类别中的所有项目。

数据库表关系如下:

- Category > SubCategory > StockItems

DDLHTML.DropDownList,它会传回所选类别,并由Controller使用Request["DDLName"]接听。那么是否可以使用stockitem将属于所选类别的LINQ作为视图返回到视图?

通过以下尝试,我目前得到:

  

对象引用未设置为对象的实例

课程如下 -

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; }
}

Controller目前有以下索引 -

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);

1 个答案:

答案 0 :(得分:0)

确定最终......最后的控制器类如下 -

  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);
    }

为你的评论干杯。如果有其他人遇到同样的问题,很乐意详细说明。