Мне нужно отправить List
Почтальону. Вот как я это делаю:
Почтальон:
{
"CategoryId": "2139",
"ListId": "1",
"ProductsToCompare": [0, 1]
}
Запрос:
[HttpPost]
public async Task<IActionResult> AddProductToComparsionList([FromBody] ProductComparsionVM comparsion)
{
return Json(await _productRepo.AddProductToComparsionList(comparsion.ProductsToCompare.Select(z => z.ProductId).ToList(), comparsion.CategoryId, comparsion.ListId));
}
Возвращает ноль. Что я делаю не так?
Редактировать 1
public async Task<ProductComparsionVM> AddProductToComparsionList(List<int> productIds, int categoryId, int? listId)
{
if (productIds == null)
return null;
var comparsionList = await _dbContext.ProductsComparsion
.AsNoTracking()
.Include(z => z.ProductsToCompare)
.FirstOrDefaultAsync(z => z.Id.Equals(listId));
Guid sessionId = default;
Guid.TryParse(_httpContextAccessor.HttpContext.Session.Id, out sessionId);
foreach(var productId in productIds)
{
if (comparsionList == null)
{
var products = _dbContext.Products.Include(z => z.ProductCategories);
comparsionList = new ProductComparsion();
comparsionList.CategoryId = products.FirstOrDefault(z => z.Id == productId).ProductCategories.FirstOrDefault().CategoryId;
comparsionList.SessionId = sessionId;
comparsionList.UserId = _userManager.GetUserAsync(_httpContextAccessor.HttpContext.User).GetAwaiter().GetResult().Id;//!
comparsionList.ProductsToCompare = new List<ProductToCompare>();
comparsionList.ProductsToCompare.Add(new ProductToCompare { ProductId = productId });
}
else if (!comparsionList.ProductsToCompare.Any(z => z.ProductId == productId))
{
comparsionList.ProductsToCompare.Add(new ProductToCompare { ProductId = productId });
comparsionList.CategoryId = _dbContext.Products.FirstOrDefault(z => z.Id == productId).ProductCategories.FirstOrDefault().CategoryId;
comparsionList.SessionId = sessionId;
comparsionList.UserId = _userManager.GetUserAsync(_httpContextAccessor.HttpContext.User).GetAwaiter().GetResult().Id;
}
}
await _dbContext.AddAsync(comparsionList);
await _dbContext.SaveChangesAsync();
return new ProductComparsionVM
{
CategoryId = _dbContext.Categories.FirstOrDefault(z => z.Id == comparsionList.CategoryId).Id,
ProductsToCompare = comparsionList.ProductsToCompare.ToList()
};
}
public class ProductComparsionVM
{
public int CategoryId { get; set; }
public int? ListId { get; set; }
public List<ProductToCompare> ProductsToCompare { get; set; }
}
public class ProductToCompareVM
{
public ProductComparsion ProductComparsion { get; set; }
public ProductVM Product { get; set; }
}