简体   繁体   中英

How to count multiple cell values individually and then assign to a list using linq

I have a table Products

Id, Name, Photo, Price,Total_Products

Now my requirement is the column Total_Products contain value based upon the products.

for example 
Id    Name              Photo                          Price    Total_Products
1     Samsung Galaxy    ~/Products/samsung-galaxy.jpg  15000    1
2     Apple IPhone      ~/Products/IPhone.jpg          20000    2
3     Nokia Lumia       ~/Products/Nokia-Lumia.jpg     10000    0
4     ...........................................................
5     ...........................................................

Here I just want to count the no of each product using Total_Products and I want to display Out of Stock message just above the image of Product. I am having the action method

public ActionResult Products()
    {                       
        return View(db.Products.ToList());
    }

The above code gives me all the particulars I want to count each product value if it exceeds greater than 1 then I want a msg just above the image saying Out of Stock 在此处输入图片说明

I'm not entirely sure if this is what you're after, but you'd probably want something like:

@foreach (var product in Model) 
{
    <div class="product">
        @if (product.Total_Products < 1)
        {
            <div>Out of Stock</div>
        }
        <img src="@product.Photo"/>
        <div>@product.Name</div>
    </div>
}

EDIT

To decrement your total products when an order is submitted, you'd end up with something like this (heavily simplified):

[HttpPost]
public ActionResult Order(SubmitOrderModel model) 
{
    var product = db.Products.Single(p => p.Id = model.productId);

    // create your order record
    // ...

    // update inventory
    product.Total_Products -= 1;
    db.SubmitChanges();
    return RedirectToAction("OrderSuccess");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM