In this article I will explain with an example, how to display
Grand Total in Footer in
ASP.Net Core (.Net Core 8)
MVC.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Model
The Model class consists of following properties.
public class Product
{
public int OrderID { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.Data.SqlClient;
Controller
The Controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, the records are fetched from the
Orders and
Product Tables using
SqlDataReader and then using
WHILE Loop, the records are copied into the Generic List collection of
Product class objects.
Finally, the Generic List collection of Product class objects is returned to the View.
public class HomeController : Controller
{
// GET: Home
public IActionResult Index()
{
string sql = "SELECT TOP 10 OrderID,";
sql += "(SELECT ProductName FROM Products WHERE ProductID = details.ProductId) ProductName,";
sql += "(Quantity * UnitPrice) Price";
sql += " FROM [Order Details] details";
sql += " ORDER BY OrderID";
string constr = @"Data Source= .\SQL2019;Initial Catalog= Northwind;uid=sa;pwd=pass@123";
List<Product> products = new List<Product>();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
products.Add(new Product
{
OrderID = Convert.ToInt32(sdr["OrderID"]),
ProductName = sdr["ProductName"].ToString(),
Price = Convert.ToDecimal(sdr["Price"])
});
}
}
con.Close();
return View(products);
}
}
}
}
View
HTML Markup
Inside the View, in the very first line the Product class is declared as Model for the View.
For displaying the records, an
HTML Table is used. A loop will be executed over the rows of the
DataTable which will generate the
HTML Table rows with the records.
Note: The Price column is formatted to display only two decimal places using the ToString(“N2”) function.
The last row of the
HTML Table is the
Footer Row, where the Grand Total i.e. the Sum of the
Price of all the Products is calculated using
Lambda Expression and displayed.
@using Calculate_Total_Table_Core_MVC.Model;
@model List<Product>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table cellpadding="0" cellspacing="0">
<tr>
<th>Order ID</th>
<th>Product Name</th>
<th>Price</th>
</tr>
@foreach (Product product in Model)
{
<tr>
<td>@product.OrderID</td>
<td>@product.ProductName</td>
<td>@product.Price.ToString("N2")</td>
</tr>
}
<tr>
<td colspan="2" align="right">Total</td>
<td>@Model.Select(p => p.Price).Sum().ToString("N2")</td>
</tr>
</table>
</body>
</html>
Screenshot
Downloads