[英]Filter products based on multiple check boxes
我在電子商務網站上工作。 我想根據多個復選框過濾產品。 我使用 ajax。 它將復選框的 ID 發送到 controller。 但是selected
的計數為零,如圖所示。 這段代碼有什么問題?
Ajax:
<script type="text/javascript">
$(function () {
$('.filterprod').click(function () {
var ProdID = "";
$('.checks').each(function () {
if ($(this).is(':checked')) {
ProdID += $(this).val() + ",";
}
});
var data = {};
data.Id = ProdID.slice(0, ProdID.length - 1);
$.ajax({
url: '/Shop/GetProd',
method: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(data),
success: function (response) {
$("#Prodlist").remove();
},
error: function (err, response) {
console.log(err, response);
alert(err, response.responseText);
}
})
});
});
</script>
Controller:
[HttpPost]
public JsonResult GetProd(string Id)
{
var ids = new List<int>();
IQueryable<Product> prods = null;
if (!string.IsNullOrEmpty(Id))
{
for (int i = 0; i < Id.Split(',').Length; i++)
{
ids.Add(Convert.ToInt32(Id.Split(',')[i]));
}
prods =_context.Products.Where(t => ids.Contains(t.id));
}
else
{
prods = _context.Products.Take(5);
}
var selected = (from v in prods
select new
{
v.ProdName,
v.Price,
v.Description
}).ToList();
return Json(selected, JsonRequestBehavior.AllowGet);
}
嘗試在這樣的控制台中執行此操作: https://dotnetfiddle.net/AMwxiP
using System;
using System.Collections.Generic;
using System.Linq;
public class Product
{
public int Id { get; set; }
public string ProdName { get; set; }
public decimal? Price { get; set; }
public string Description { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
IQueryable<Product> products = (new List<Product> {
new Product
{
Id = 1,
},
new Product
{
Id = 2,
}
}).AsQueryable<Product>();
var Id = "1,2";
var ids = new List<int>();
IQueryable<Product> prods = null;
if (!string.IsNullOrEmpty(Id))
{
for (int i = 0; i < Id.Split(',').Length; i++)
{
ids.Add(Convert.ToInt32(Id.Split(',')[i]));
}
prods = products.Where(t => ids.Contains(t.Id));
}
else
{
prods = products.Take(5);
}
var selected = (from v in prods
select new
{
v.ProdName,
v.Price,
v.Description
}).ToList();
Console.WriteLine(selected.Count);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.