Hi nabilabolo,
Check the below example.
SQL
CREATE TABLE [dbo].[Hobbies](
[HobbyId] [INT] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Hobby] [VARCHAR](50) NOT NULL,
[IsSelected] [BIT] NOT NULL,
[CheckedDateTime] DATETIME
)
Model
public class CheckModel
{
public int Id { get; set; }
public string Hobby { get; set; }
public bool IsChecked { get; set; }
public DateTime DateTime { get; set; }
}
Namespaces
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
return View(GetHobbies());
}
[HttpPost]
public JsonResult UpdateHobby(string id)
{
UpdateHobby(id, DateTime.Now.ToString());
return Json("");
}
[HttpPost]
public JsonResult GetUpdatedHobby()
{
int id = 0;
foreach (CheckModel hobby in GetHobbies())
{
id = hobby.Id;
DateTime lastUpdated = hobby.DateTime;
if (lastUpdated != DateTime.MinValue)
{
if (DateTime.Now.Subtract(lastUpdated).Milliseconds >= 5000)
{
UpdateHobby(hobby.Id.ToString(), "");
break;
}
}
}
return Json(id);
}
private static void UpdateHobby(string id, string date)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "UPDATE Hobbies SET CheckedDateTime = @Date WHERE HobbyId = @Id";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("@Id", id);
cmd.Parameters.AddWithValue("@Date", !string.IsNullOrEmpty(date) ? Convert.ToDateTime(date) : (object)DBNull.Value);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
private static List<CheckModel> GetHobbies()
{
List<CheckModel> items = new List<CheckModel>();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "SELECT * FROM Hobbies";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new CheckModel
{
Id = Convert.ToInt32(sdr["HobbyId"]),
Hobby = sdr["Hobby"].ToString(),
IsChecked = Convert.ToBoolean(sdr["IsSelected"]),
DateTime = Convert.ToDateTime(sdr["CheckedDateTime"])
});
}
}
con.Close();
}
}
return items;
}
}
View
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('#tblHobbies input[type=checkbox]').on('click', function () {
var id = $(this).closest('tr').find('td').eq(0).html().trim();
if ($(this).is(':checked')) {
$.ajax({
type: "POST",
url: "/Home/UpdateHobby",
data: '{id: "' + id + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) { }
});
}
});
setInterval(function () {
$.ajax({
type: "POST",
url: "/Home/GetUpdatedHobby",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$('#tblHobbies tbody tr').each(function () {
if ($(this).find('td').eq(0).html().trim() == response) {
$(this).find('input[type=checkbox]').prop("checked", false);
}
});
}
});
}, 5000);
});
</script>
<table id="tblHobbies">
<thead>
<tr>
<th>Id</th>
<th>Hobby</th>
<th>Selected</th>
</tr>
</thead>
<tbody>
<% foreach (var hobby in Model)
{ %>
<tr>
<td><%: hobby.Id%></td>
<td><%: hobby.Hobby%></td>
<td><%:Html.CheckBoxFor(m => hobby.IsChecked)%></td>
</tr>
<% } %>
</tbody>
</table>
</body>