在ASP.NET MVC 5,C#和实体框架中选择从下拉列表选择中的数据
我有一个数据库,该数据库可以通过从中获取数据的实体框架访问。我有两个下拉列表,我希望能够根据用户选择来过滤我的数据。例如,数据库中的我的表被称为products
,在一个下拉列表中,我希望能够按公司过滤产品,对于其他下拉列表,我希望能够通过类别。或者,如果从两个下拉列表中进行选择,则根据该标准过滤数据。
我的产品
表具有公司的companyId
, categoryId 类别的。它们都是其他表的外国键(如下所示):
for
companyId
在products
表中,引用表为condiss> companies
具有列CompaniD
(主键)和品牌名称
(这是在下拉列表中显示的内容)for
categoryId
products 表,引用表称为<代码> ItemCategories 具有列categoryId
(主键)和category
(这是下拉列表中显示的内容)
注意:我更喜欢这种方式,因为公司和项目类别可以定期更改,我喜欢能够更新表而不是代码,但我认为它们被读成一个int,不能转换为字符串(至少这就是我的错误消息所说的),这就是为什么我认为我很难过。
我已经尝试了我能找到的所有东西的500种不同变化,但无济于事。我得到的最接近的是我在其中一个下拉列表中选择了一个项目,然后返回了一个带有0个结果的列表。我尝试过的其他所有内容都会给我错误消息,或者在我单击过滤器时根本没有任何操作。让我感到困惑的是我看到的很多示例在它们的代码中使用了类似的东西:
products = products.Where(x => x.CompanyID == (prodCompany));
它不会让我使用==,因为它
不能应用于INT类型的操作数?和字符串
我将在显示代码之前添加最后一点,这是我有数百种产品,必须为它们使用页面列表,否则加载和冻结时间太长了。这是使过滤工作的另一个棘手的部分是必须如何合并分页列表。我的工作正常很好,但是当它没有过滤器时,它目前按productid的Orderby方法对其进行分类。我不确定这是否会影响我的结果,因为我想通过compandID或categoryId过滤(但希望它仍然对productid的过滤结果分类)?
最终摘要:我正在将ASP.NET MVC 5与实体框架和C#一起使用,我希望能够根据公司清单下拉或类别列表下拉的选择中的“索引”视图中的“索引”视图中的数据过滤数据(或两者兼而有之,如果没有选择,则显示所有产品(带有分页列表)。这是我当前的代码:
我的模型类product
:
public partial class Product
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Product()
{
this.ProductOrders = new HashSet<ProductOrder>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Display(Name = "Product ID")]
public int ProductID { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Date")]
public Nullable<System.DateTime> Date_Entered { get; set; }
[Display(Name = "Product Code")]
public string Product_Code { get; set; }
public string Description { get; set; }
[Display(Name = "Company")]
public Nullable<int> CompanyID { get; set; }
[AllowHtml]
[Display(Name = "Category")]
public Nullable<int> CategoryID { get; set; }
[Display(Name = "Amt In Stock")]
public Nullable<int> Amt_In_Stock { get; set; }
[Display(Name = "Qty Available")]
public Nullable<int> Qty_Available { get; set; }
[Display(Name = "Image")]
public string ImageUrl { get; set; }
public virtual Company Company { get; set; }
public virtual ItemCategory ItemCategory { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ProductOrder> ProductOrders { get; set; }
}
这是我的productscontroller
:
namespace AMS_ITAMSdb.Controllers
{
public class ProductsController : Controller
{
private ItamsEntities db = new ItamsEntities();
// GET: Products
public ActionResult Index(string prodCompany, string prodCategory, int? page)
{
ViewBag.prodCompany = new SelectList(db.Companies, "CompanyID", "Brand_Name");
ViewBag.prodCategory = new SelectList(db.ItemCategories, "CategoryID", "Category");
var prod = from p in db.Products
select p;
if (!String.IsNullOrEmpty(prodCompany))
{
//Filter results based on company selected.
var pageNumber = page ?? 1;
var pageSize = 15;
prod = prod.Where(x => x.CompanyID.Equals(prodCompany));
var product = db.Products.OrderBy(x => x.ProductID).ToPagedList(pageNumber, pageSize);
return View(product);
}
if (!String.IsNullOrEmpty(prodCategory))
{
//Filter results based on company selected.
var pageNumber = page ?? 1;
var pageSize = 15;
prod = prod.Where(x => x.CategoryID.Equals(prodCategory));
var product = db.Products.OrderBy(x => x.ProductID).ToPagedList(pageNumber, pageSize);
return View(product);
}
else
//var product = db.Products.OrderBy(x=>x.ProductID).ToList();
{
var pageNumber = page ?? 1;
var pageSize = 15;
var product = db.Products.OrderBy(x => x.ProductID).ToPagedList(pageNumber, pageSize);
return View(product);
}
}
}
}
最后我的索引视图:
@using AMS_ITAMSdb.Models;
@using PagedList;
@using PagedList.Mvc;
@model PagedList.IPagedList<Product>
@{
ViewBag.Title = "Index";
}
<h2>Products</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
@using (Html.BeginForm("Index", "Products", FormMethod.Get))
{
<p>
Company: @Html.DropDownList("prodCompany", "All")
Category: @Html.DropDownList("prodCategory", "All")
<input type="submit" value="Filter" />
</p>
}
<table class="table">
<tr>
<th>
Date
</th>
<th>
Product Code
</th>
<th>
Description
</th>
<th>
Amt In Stock
</th>
<th>
Qty Available
</th>
<th>
Image
</th>
<th>
Company
</th>
<th>
Category
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Date_Entered)
</td>
<td>
@Html.DisplayFor(modelItem => item.Product_Code)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.Amt_In_Stock)
</td>
<td>
@Html.DisplayFor(modelItem => item.Qty_Available)
</td>
<td>
<img src="~/Images/@item.ImageUrl" width="100" height="100" />
</td>
<td>
@Html.DisplayFor(modelItem => item.Company.Brand_Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.ItemCategory.Category)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ProductID }) |
@Html.ActionLink("Details", "Details", new { id = item.ProductID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ProductID })
</td>
</tr>
}
</table>
<link href="~/Content/PagedList.css" rel="stylesheet" />
<div></div>
(Page @(Model.PageCount < Model.PageNumber ? 0: Model.PageNumber)/@Model.PageCount)
@Html.PagedListPager(Model, page => Url.Action("Index", new { page = page }))
I have a database which is accessed through Entity Framework where I'm getting my data from. I have two drop down lists that I want to be able to filter my data with based on the users selection. For example, my table in the database is called Products
and on one dropdown list I want to be able to filter the products by company and for the other dropdown list I want to be able to filter the products by category. Or if a selection is made from both dropdowns, to filter data based on that criteria.
My Products
table has columns CompanyID
for the company and CategoryID
for the category. They are both foreign keys to other tables (as shown below):
For
CompanyID
in theProducts
table, the referenced table isCompanies
which has columnsCompanyID
(primary key), andBrand Name
(which is what is displayed in the dropdown list)For
CategoryID
in theProducts
table, the referenced table is calledItemCategories
which has columnsCategoryID
(primary key) andCategory
(which is what is displayed in the dropdown list)
Note: I prefer to keep it this way because the companies and item categories can change periodically and I like being able to update the tables rather than the code, but I think they get read as an int and cannot be converted to a string (at least that's what my error messages have said) which is why I think I'm having such a hard time.
I've tried what seems like 500 different variations of everything I could find, but to no avail. The closest I got was I selected an item on one of the dropdown lists and it returned a list with 0 results. Everything else I've tried it gives me error messages or it just doesn't do anything at all when I click filter. What's confusing me is alot of the examples I've seen uses something like this in their code:
products = products.Where(x => x.CompanyID == (prodCompany));
It won't let me use the == because it
Cannot be applied to operands of type int? and string
Last bit I'll add before I show my code so far is I have hundreds of products and have to use a paged list for them or else it takes too long to load and freezes up on me. That's been the other tricky part getting the filtering to work is how the paged list has to be incorporated. I have it working perfectly fine, but when it doesn't have a filter, it currently sorts by an OrderBy method by ProductID. I'm not sure if that is effecting my results or not since I want to filter by CompanyID or CategoryID (but hope is that it still sorts the filtered results by the ProductID)??
Final summary: I'm using ASP.NET MVC 5 with Entity Framework and C#, I want to be able to filter data in my products table in the "Index" view based on a selection from a company list dropdown or a category list dropdown (or both) and if no selection is made it displays all the products (with the paged list). Here is my code as it is currently:
My model class Product
:
public partial class Product
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Product()
{
this.ProductOrders = new HashSet<ProductOrder>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Display(Name = "Product ID")]
public int ProductID { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Date")]
public Nullable<System.DateTime> Date_Entered { get; set; }
[Display(Name = "Product Code")]
public string Product_Code { get; set; }
public string Description { get; set; }
[Display(Name = "Company")]
public Nullable<int> CompanyID { get; set; }
[AllowHtml]
[Display(Name = "Category")]
public Nullable<int> CategoryID { get; set; }
[Display(Name = "Amt In Stock")]
public Nullable<int> Amt_In_Stock { get; set; }
[Display(Name = "Qty Available")]
public Nullable<int> Qty_Available { get; set; }
[Display(Name = "Image")]
public string ImageUrl { get; set; }
public virtual Company Company { get; set; }
public virtual ItemCategory ItemCategory { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ProductOrder> ProductOrders { get; set; }
}
Here is my ProductsController
:
namespace AMS_ITAMSdb.Controllers
{
public class ProductsController : Controller
{
private ItamsEntities db = new ItamsEntities();
// GET: Products
public ActionResult Index(string prodCompany, string prodCategory, int? page)
{
ViewBag.prodCompany = new SelectList(db.Companies, "CompanyID", "Brand_Name");
ViewBag.prodCategory = new SelectList(db.ItemCategories, "CategoryID", "Category");
var prod = from p in db.Products
select p;
if (!String.IsNullOrEmpty(prodCompany))
{
//Filter results based on company selected.
var pageNumber = page ?? 1;
var pageSize = 15;
prod = prod.Where(x => x.CompanyID.Equals(prodCompany));
var product = db.Products.OrderBy(x => x.ProductID).ToPagedList(pageNumber, pageSize);
return View(product);
}
if (!String.IsNullOrEmpty(prodCategory))
{
//Filter results based on company selected.
var pageNumber = page ?? 1;
var pageSize = 15;
prod = prod.Where(x => x.CategoryID.Equals(prodCategory));
var product = db.Products.OrderBy(x => x.ProductID).ToPagedList(pageNumber, pageSize);
return View(product);
}
else
//var product = db.Products.OrderBy(x=>x.ProductID).ToList();
{
var pageNumber = page ?? 1;
var pageSize = 15;
var product = db.Products.OrderBy(x => x.ProductID).ToPagedList(pageNumber, pageSize);
return View(product);
}
}
}
}
Finally my index view:
@using AMS_ITAMSdb.Models;
@using PagedList;
@using PagedList.Mvc;
@model PagedList.IPagedList<Product>
@{
ViewBag.Title = "Index";
}
<h2>Products</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
@using (Html.BeginForm("Index", "Products", FormMethod.Get))
{
<p>
Company: @Html.DropDownList("prodCompany", "All")
Category: @Html.DropDownList("prodCategory", "All")
<input type="submit" value="Filter" />
</p>
}
<table class="table">
<tr>
<th>
Date
</th>
<th>
Product Code
</th>
<th>
Description
</th>
<th>
Amt In Stock
</th>
<th>
Qty Available
</th>
<th>
Image
</th>
<th>
Company
</th>
<th>
Category
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Date_Entered)
</td>
<td>
@Html.DisplayFor(modelItem => item.Product_Code)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.Amt_In_Stock)
</td>
<td>
@Html.DisplayFor(modelItem => item.Qty_Available)
</td>
<td>
<img src="~/Images/@item.ImageUrl" width="100" height="100" />
</td>
<td>
@Html.DisplayFor(modelItem => item.Company.Brand_Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.ItemCategory.Category)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ProductID }) |
@Html.ActionLink("Details", "Details", new { id = item.ProductID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ProductID })
</td>
</tr>
}
</table>
<link href="~/Content/PagedList.css" rel="stylesheet" />
<div></div>
(Page @(Model.PageCount < Model.PageNumber ? 0: Model.PageNumber)/@Model.PageCount)
@Html.PagedListPager(Model, page => Url.Action("Index", new { page = page }))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
经过将近两个星期的头撞到墙上试图解决这个问题之后,我终于想出了我在这里看到的其他问题的尝试,网址为:下拉列表选择的值我发现。我的代码真的很接近,最终只是一个小调整,这就是我认为会发生的情况。无论如何,我发现的修复程序是在控制器上,我将.tostring()添加到过滤器中,这使我可以在字符串中使用int并将“等价”更改为“包含”。我做的其他几个次要更改是我添加了另一个字符串(字符串CurrentFilter),并添加了一个If语句。我在控制器中更改的新代码是:
在我的索引视图上,我只需要在底部进行分页元素的一个微小的更改:
After nearly two weeks of banging my head on the wall trying to figure this out, I finally figured it out from trying something I saw on another question on here at: dropdown list selected value that I found. My code was really close, it ended up just being a minor tweak which is what I thought would happen smh. Anyways, the fix I found was on my controller where I added .ToString() to my filter which allowed me to use the int in the string and changed the 'Equals' to 'Contains'. A couple other minor changes I made was I added another string (string currentFilter) and I added an if statement. New code I changed in the controller is:
and on my index view I had to just make one tiny change at the bottom for the paging element: