Refresh realtime data at intervals in ASP.Net MVC using jQuery AJAX

sangyongjin88
 
on May 05, 2022 11:01 PM
Sample_132473.zip
1078 Views

Hi,

I try to make real time updating email from my email account using Json. Email updating is not working now. I setup Intervals (1 second) for starting Json code, but not updating transferred new emails from my own email. I attached code and please tell me the solutions.

I want to make it when we receive new email using outlook, It automatically added new email rows in that table and list.

Please help me.

Thank you.

Index.cshtml

<div class="card mb-4" style="font-size:15px;">
    <div class="card-header">
        <i class="fas fa-table me-1"></i>
        Employee Information
    </div>
    <div class="card-body">
        <table id="datatablesSimple">
            <thead>
                <tr>
                    <th>Email</th>
                    <th>Subject</th>
                    <th></th>
                </tr>
            </thead>
            <tfoot>
                <tr>
                    <th>Email</th>
                    <th>Subject</th>
                    <th></th>
                </tr>
            </tfoot>
            <tbody>
                @foreach (var item in Model.OrderByDescending(x => x.MessageNumber))
                {
                    <tr>
                        <td>@Html.Raw(item.CustomerInfo)</td>
                        <td>@Html.Raw(item.Subject)</td>
                        <td>
                            @Html.ActionLink("Details", "CustomDetails", new { id = item.MessageNumber }) |
                            @Html.ActionLink("Delete", "Delete", new { id = item.MessageNumber })
                        </td>
                    </tr>
                }

            </tbody>
        </table>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest" crossorigin="anonymous"></script>
<script src="~/AdminStyle/js/datatables-simple-demo.js"></script>

@section Scripts {
    <script type="text/javascript">
        window.setInterval(function () {
            Edit01()
        }, 1000); // 1 Seconds

        function Edit01() {
            $.ajax({
                url: '@Url.Action("Edit01", "POPEmails")',
                type: "GET",            

            }).done(function (result) {
                var html = result.NumberOfLikes;

                document.getElementById("GetLikeValues").innerHTML = html;
            });
        }
    </script>
}

POPEmailsController.cs

public ActionResult Index()
{          
    return View(db.POPEmails.ToList());
}
 
[HttpGet]    
public JsonResult Edit01()
{
    Pop3Client pop3Client;
    pop3Client = new Pop3Client();
    //pop3Client.Connect("pop3.live.com", 995, true);
    pop3Client.Connect("outlook.office365.com", 995, true);
    pop3Client.Authenticate("EMAIL", "PW");
 
    int count001 = db.POPEmails.Count();
    int count = pop3Client.GetMessageCount(); //total count of email in MessageBox
    int Newcount = count - count001;
    var Emails = new List<POPEmail>(); //POPEmail type
 
    for (int i = count001; i < count + 1; i++)
    {
        var Cuidado = db.POPEmails.Where(x => x.MessageNumber == i).FirstOrDefault();
 
        if (Cuidado == null)
        {
            Message message = pop3Client.GetMessage(i);
 
            POPEmail pOPEmail = new POPEmail();
 
            pOPEmail.MessageNumber = i;
            pOPEmail.Subject = message.Headers.Subject;
            pOPEmail.DateSent = message.Headers.DateSent;
            pOPEmail.FromEmail = string.Format("<a href = 'mailto:{1}'>{0}</a>", message.Headers.From.DisplayName, message.Headers.From.Address);
            pOPEmail.AddiationalInfo = message.Headers.From.DisplayName;
            pOPEmail.CustomerInfo = message.Headers.From.Address;
 
            MessagePart body = message.FindFirstHtmlVersion();
 
            MessagePart body01 = message.FindFirstPlainTextVersion();
 
            if (body != null)
            {
                pOPEmail.Body = body.GetBodyAsText();
            }
            else
            {
                if (body01 != null)
                {
                    pOPEmail.Body = body01.GetBodyAsText();
                }
            }
 
            db.POPEmails.Add(pOPEmail);
            db.SaveChanges();
 
            List<MessagePart> attachments = message.FindAllAttachments();
            foreach (MessagePart attachment in attachments)
            {
                FileAttached fileAttached = new FileAttached();
                fileAttached.FieKey = i;
                fileAttached.FileName = attachment.FileName;
                fileAttached.ContentType = attachment.ContentType.MediaType;
                fileAttached.Contents = attachment.Body;
 
                db.FileAttacheds.Add(fileAttached);
                db.SaveChanges();
            }
        }
    }
 
    var Tempp = db.POPEmails.Select(x => new { x.Subject, x.CustomerInfo }).Distinct().ToArray();
    var CountTemp = db.Customerinfoes.Count();
    for (int i = CountTemp; i < Tempp.Length; i++)
    {
        var Indexfun01 = Tempp[i].Subject;
        var Indexfun02 = Tempp[i].CustomerInfo;
        var Temp001 = db.POPEmails.Where(x => x.Subject == Indexfun01 && x.CustomerInfo == Indexfun02).FirstOrDefault();
 
        var IsCUsemail = db.Customerinfoes.Where(x => x.Emails == Indexfun02 && x.Subject == Indexfun01).FirstOrDefault();
 
        if (IsCUsemail == null)
        {
            Customerinfo customerinfo = new Customerinfo();
 
            customerinfo.Emails = Tempp[i].CustomerInfo;
            customerinfo.Subject = Tempp[i].Subject;
            customerinfo.Name = Temp001.AddiationalInfo;
 
            db.Customerinfoes.Add(customerinfo);
            db.SaveChanges();
        }
    }
 
    return Json(db.POPEmails.ToList());
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on May 07, 2022 03:21 AM

Hi sangyongjin88,

You need to refresh the table data on ajax success.

Refer below example.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

Model

public class CustomerModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}

Namespaces

using System.Configuration;
using System.Data.SqlClient;

Controller

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

    [HttpGet]
    public JsonResult Edit01()
    {
        var customers = GetCustomers();
        return Json(customers, JsonRequestBehavior.AllowGet);
    }

    private List<CustomerModel> GetCustomers()
    {
        List<CustomerModel> customers = new List<CustomerModel>();
        string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        string query = "SELECT TOP 5 CustomerID,ContactName,Country FROM Customers ORDER BY NEWID()";
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                con.Open();
                SqlDataReader sdr = cmd.ExecuteReader();
                while (sdr.Read())
                {
                    customers.Add(new CustomerModel
                    {
                        Id = sdr["CustomerID"].ToString(),
                        Name = sdr["ContactName"].ToString(),
                        Country = sdr["Country"].ToString()
                    });
                }
                con.Close();
            }
        }

        return customers;
    }
}

View

@model IEnumerable<Refresh_Interval_Email.Models.CustomerModel>

@{
    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(function () {
                Edit01()
            }, 1000);
        });

        function Edit01() {
            $.ajax({
                url: '@Url.Action("Edit01", "Home")',
                type: "GET",
                data: {},
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    $('#datatablesSimple tbody').empty();
                    var tr = "";
                    $.each(response, function (index, item) {
                        tr += "<tr><td>" + item.Name + "</td>";
                        tr += "<td>" + item.Country + "</td></tr>";
                    });
                    $('#datatablesSimple tbody').append(tr);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        }
    </script>
</head>
<body>
    <table id="datatablesSimple">
        <thead>
            <tr>
                <th>Name</th>
                <th>Country</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.OrderByDescending(x => x.Id))
            {
                <tr>
                    <td>@Html.Raw(item.Name)</td>
                    <td>@Html.Raw(item.Country)</td>
                </tr>
            }
        </tbody>
    </table>
</body>
</html>

Sereenshot