Display two columns total in Third on Button Click in ASP.Net MVC

nabilabolo
 
on Mar 24, 2021 01:48 AM
Sample_542008.zip
2646 Views

Hi,

I have a table that looks like below.

When i click calculate, it will calculate each row using formula = cost/qty * 100 and display on total column in MVC.

How can i do that? 

quantity     cost   total

  30           5    

 100          21

       calculate

Thanks

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Mar 24, 2021 02:29 AM
on Jan 04, 2022 10:37 AM

Hi nabilabolo,

Check this example. Now please take its reference and correct your code.

Model

public class ProductModel
{
    public decimal Quantity { get; set; }
    public decimal Cost { get; set; }
    public decimal Total { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View(GetProducts());
    }

    [HttpPost]
    public ActionResult Calculate()
    {
        List<ProductModel> products = GetProducts();
        foreach (ProductModel product in products)
        {
            product.Total = Math.Round(((product.Cost / product.Quantity) * 100), 2);
        }
        return View("Index", products);
    }

    private List<ProductModel> GetProducts()
    {
        List<ProductModel> products = new List<ProductModel>();
        products.Add(new ProductModel { Quantity = 30, Cost = 5 });
        products.Add(new ProductModel { Quantity = 100, Cost = 21 });

        return products;
    }
}

View

@using Row_Calculation.Models;
@model IEnumerable<ProductModel>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <table>
        <tr>
            <th>Quantity</th>
            <th>Cost</th>
            <th>Total</th>
        </tr>

        @foreach (ProductModel product in Model)
        {
            <tr>
                <td>@product.Quantity.ToString("N0")</td>
                <td>@product.Cost.ToString("N0")</td>
                <td>@product.Total.ToString("N0")</td>
            </tr>
        }
    </table>
    @using (Html.BeginForm("Calculate", "Home", FormMethod.Post))
    {
        <input type="submit" value="Calculate" />
    }
</body>
</html>

Output

Quantity Cost Total

   30          5      16.66

  100         21    21.00