Hi rani,
Use JavaScript setInterval function.
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.SqlClient;
Controller
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult GetData()
{
List<Customer> customers = new List<Customer>();
string constr = @"Server=.\SQL2014;DataBase=Northwind;UID=sa;PWD=pass@123";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 5 CustomerID,ContactName,City,Country FROM Customers ORDER BY NEWID()", con))
{
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
customers.Add(new Customer
{
Id = sdr["CustomerID"].ToString(),
Name = sdr["ContactName"].ToString(),
City = sdr["City"].ToString(),
Country = sdr["Country"].ToString()
});
}
con.Close();
}
}
return Json(customers);
}
public class Customer
{
public string Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
}
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<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 () {
setInterval(PopulateData, 1000);
});
function PopulateData() {
$.ajax({
type: 'POST',
url: '/Home/GetData',
data: {},
success: function (data) {
var tbody = document.getElementById('tblCustomers').getElementsByTagName('tbody')[0];
tbody.innerHTML = "";
$.each(data, function (i, item) {
var newRow = tbody.insertRow();
var newCell = newRow.insertCell();
var newText = document.createTextNode(item.id);
newCell.appendChild(newText);
newCell = newRow.insertCell();
newText = document.createTextNode(item.name);
newCell.appendChild(newText);
newCell = newRow.insertCell();
newText = document.createTextNode(item.city);
newCell.appendChild(newText);
newCell = newRow.insertCell();
newText = document.createTextNode(item.country);
newCell.appendChild(newText);
});
}
});
}
</script>
</head>
<body>
<table id="tblCustomers">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>City</th>
<th>Country</th>
</tr>
</thead>
<tbody></tbody>
</table>
</body>
</html>
Screenshot