Hi sureshMGR,
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Namespaces
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
TempData["Data"] = GetData();
return View();
}
private DataTable GetData()
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT TOP 5 ProductID,ProductName,UnitPrice FROM Products";
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
View
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Index</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var total = 0;
$.each($('.table tr:has(td)'), function () {
var price = $(this).find('td').eq(2).html();
total = total + parseFloat(price);
});
$('#total').html(total);
});
</script>
</head>
<body>
<div>
<table class="table">
<tr>
<% foreach (DataColumn col in (TempData["Data"] as DataTable).Columns)
{ %>
<th>
<%=col.ColumnName%>
</th>
<%} %>
</tr>
<% foreach (DataRow row in (TempData["Data"] as DataTable).Rows)
{ %>
<tr>
<% foreach (DataColumn col in (TempData["Data"] as DataTable).Columns)
{ %>
<td>
<%=row[col.ColumnName]%>
</td>
<%} %>
</tr>
<%} %>
</table>
<span id="total"></span>
</div>
</body>
</html>
Screenshot