【问题标题】:Searching by category dropdownlist in ASP.NET MVC在 ASP.NET MVC 中按类别下拉列表搜索
【发布时间】:2022-01-18 14:10:33
【问题描述】:

我正在尝试通过下拉列表将产品过滤器按类别添加到我的应用程序中,但这里的问题是我正在尝试同时使用两个模型并且我不确定如何修复它,也没有如何对产品应用过滤器,产品和类别的建模如下:

 public partial class Stz_Product
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Stz_Product()
        {
            this.Stz_Cart = new HashSet<Stz_Cart>();
        }
    
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public Nullable<bool> IsActive { get; set; }
        public Nullable<bool> IsDelete { get; set; }
        public Nullable<System.DateTime> CreatedDate { get; set; }
        public Nullable<System.DateTime> ModifiedDate { get; set; }
        public string Description { get; set; }
        public string ProductImage { get; set; }
        public Nullable<bool> IsFeatured { get; set; }
        public Nullable<int> Quantity { get; set; }
        public Nullable<int> CategoryId { get; set; }
        public Nullable<decimal> Price { get; set; }
    
        public virtual Stz_Category Stz_Category { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Stz_Cart> Stz_Cart { get; set; }
    }
}
public partial class Stz_Category
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Stz_Category()
        {
            this.Stz_Product = new HashSet<Stz_Product>();
        }
    
        public int CategoryId { get; set; }
        public string CategoryName { get; set; }
        public Nullable<bool> IsActive { get; set; }
        public Nullable<bool> IsDelete { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Stz_Product> Stz_Product { get; set; }
    }
}

这个视图的控制器:

public ActionResult Category(string search, int? page)
        {
            ViewBag.CategoryList= GetCategory();
            HomeIndexViewModel model = new HomeIndexViewModel();
            return View(model.CreateModel(search, 4, page));
        }
public GenericUnitOfWork _unitOfWork = new GenericUnitOfWork();
        public List<SelectListItem> GetCategory()
        {
            List<SelectListItem> list = new List<SelectListItem>();
            var cat = _unitOfWork.GetRepositoryInstance<Stz_Category>().GetAllRecords();
            foreach (var item in cat)
            {
                list.Add(new SelectListItem { Value = item.CategoryId.ToString(), Text = item.CategoryName });
            }
            return list;
        }

HTML视图代码如下:

@model Ecommerce_Project.Models.Home.HomeIndexViewModel
@model Ecommerce_Project.DBase.Stz_Product;
@using PagedList;
@using PagedList.Mvc;
@{
    ViewBag.Title = "Category";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@{
    List<SelectListItem> data = ViewBag.CategoryList;
}
@Html.DropDownListFor(model => model.CategoryId, data, "---Select---", new { @class = "form-control" })
<div class="row producut-container">
    @foreach (var item in Model.ListOfProducts)
    {
        <div class="col-md-3 col-sm-3 col-sx-6" style="margin-bottom:8px">
            <div class="thumbnail product-item" style="height:300px">
                <img class="img-responsive" title="Cliquer pour voir les details du produit"
                     style="cursor:pointer;height:160px;width:260px" src="~/Productimg/@item.ProductImage" />
                <div class="caption">
                    <h5> @item.ProductName </h5>
                    <p> @item.Price Dh</p>
                    <p>
                        @if (item.Quantity > 0)
                        {
                            using (Html.BeginForm("AddToCart", "Home", new { productId = item.ProductId }, FormMethod.Post))
                            {
                                <button type="submit" class="pull-right"><i class="fa fa-shopping-cart"></i></button>
                            }
                        <p>En Stock </p>
                    }
                    else
                    { <p>Pas de Stock </p>}
                        <div class="product-item-badge">
                            @if (item.IsFeatured == true)
                            {
                                <p>Nouveau</p>
                            }
                            else
                            { <p>Promotion</p>}
                        </div>

                    </div>

                </div>
            </div>
        }
    <br />
    @Html.PagedListPager(Model.ListOfProducts, page => Url.Action("Category", new { page, search = Request.QueryString["search"] }), new PagedListRenderOptions() { Display = PagedListDisplayMode.IfNeeded, DisplayItemSliceAndTotal = true })
</div>

【问题讨论】:

    标签: c# html asp.net asp.net-mvc asp.net-core


    【解决方案1】:

    您可以使用&lt;form&gt;&lt;/form&gt;在控制器中提交dropdownList的值和按条件查询,然后返回结果。

    我写了一个简单的demo大家可以参考:

    模型

    public class CustomerModel
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string City { get; set; }
            public string Country { get; set; }
        }
    

    控制器

    public class HomeController : Controller
        {
            // GET: /Home/
            public IActionResult Index()
            {
                BindDropDownList();
    
                return View(Customers());
            }
    
    
            private void BindDropDownList()
            {
               //For the convenience of demonstration, I just used hard coding
                List<SelectListItem> countries = new List<SelectListItem>();
                countries.Add(new SelectListItem { Text = "Select", Value = "0" });
                countries.Add(new SelectListItem { Text = "USA", Value = "USA" });
                countries.Add(new SelectListItem { Text = "UK", Value = "UK" });
                countries.Add(new SelectListItem { Text = "China", Value = "China" });
                ViewBag.countries = countries;
    
                List<SelectListItem> cities = new List<SelectListItem>();
                cities.Add(new SelectListItem { Text = "Select", Value = "0" });
                cities.Add(new SelectListItem { Text = "London", Value = "London" });
                cities.Add(new SelectListItem { Text = "Shanghai", Value = "Shanghai" });
                cities.Add(new SelectListItem { Text = "La", Value = "La" });
                cities.Add(new SelectListItem { Text = "Birmingham", Value = "Birmingham" });
                ViewBag.cities = cities;
            }
    
    
            [HttpPost]
            public ActionResult Index(string country, string city)
            {
               //Accept the value of the drop-down list and make a conditional query
    
                List<CustomerModel> customers = Customers();
                if (country != "0")
                {
                    customers = customers.Where(x => x.Country == country).ToList();
                }
    
                if (city != "0")
                {
                    customers = customers.Where(x => x.City == city).ToList();
                }
    
                BindDropDownList();
                return View(customers);
            }
    
            private List<CustomerModel> Customers()
            {
                List<CustomerModel> customers = new List<CustomerModel>();
                customers.Add(new CustomerModel { Id = 1, Name = "Rohit", City = "Shanghai", Country = "China" });
                customers.Add(new CustomerModel { Id = 2, Name = "John", City = "London", Country = "UK" });
                customers.Add(new CustomerModel { Id = 3, Name = "Smith", City = "La", Country = "USA" });
                customers.Add(new CustomerModel { Id = 4, Name = "Lily", City = "London", Country = "UK" });
                customers.Add(new CustomerModel { Id = 5, Name = "Ching", City = "Birmingham", Country = "UK" });
    
                return customers;
            }
        }
    

    查看

    @model List<DropdownListTest2.Models.CustomerModel>
    
        <div>   
    
             @* use `<form>` to submit the value of dropdownlist*@
    
            <form asp-controller="Home" asp-action="Index">
                Country: <select asp-items="@ViewBag.countries" name="country"></select>
                City : <select asp-items="@ViewBag.cities" name="city"></select>
                <input type="submit" value="Search" />
            </form>
            <hr />
            <table>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>City</th>
                    <th>Country</th>
                </tr>
                @foreach (var customer in @Model)
                {
                    <tr>
                        <td>@customer.Id</td>
                        <td>@customer.Name</td>
                        <td>@customer.City</td>
                        <td>@customer.Country</td>
                    </tr>
                }                    
            </table>
        </div>
    

    【讨论】:

      猜你喜欢
      • 2021-05-01
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多