javascript - Real time insertion of data in mvc - Stack Overflow

I have a news project with ment feature. Any one who add a ment can see his ment immediately without re

I have a news project with ment feature. Any one who add a ment can see his ment immediately without reloading the page ( using ajax ). The problem is that when user1 ( for example ) ment on post1 , only user1 can see his ment immediately but all other users need to reload the page to see the ment of user1. How can I solve this problem ?

The code I am using to get the ment :

$(function () {
  $("#AddComment").click(function () {

  var CommentText = document.getElementById("CommetForm").innerHTML;
    var UserName = document.getElementById("UserName").innerHTML;
    var PostId = document.getElementById("PostId").innerHTML;


       $.ajax({
                url: '/PostComment/AddComment',
                type: 'POST',
                dataType: 'json',
                cache: false,
                data: { "PostId": PostId, "CommentText": OrignalCommentText },
                success: function (data)
                {
                    if (data == "P") // Commet Stored on database successfully
                    {
                    document.getElementById("PostComments-" + PostId).innerHTML += 
                    "<li>" +
                                    "<div class='media'>" +
                                        "<div class='media-body'>" +
                                            "<a href='' class='ment-author'>"+UserName+"</a>" +
                                            "<span class='CommetText' id='CommentText-" + PostId + "'>" + CommentText + "</span>" +
                                        "</div>" +
                                    "</div>" +
                                "</li>";

                    }

                    else // Some Error occur during storing database
                    {

                        document.getElementById("CommentError-" + PostId).innerHTML = "\nSomething went wrog, please try agin";

                    }



                }
            });
});
});

And This code for storing ment in database :

  private SocialMediaDatabaseContext db = new SocialMediaDatabaseContext();

  [HttpPost]
    public JsonResult AddComment(string PostId, string CommentText)
    {
        try
        {
            Users CurrentUser = (Users)Session["CurrentUser"];
            PostComment postment = new PostComment();


            CommentText = System.Uri.UnescapeDataString(CommentText);


            postment.PostId = int.Parse(PostId);
            postment.CommentFromId = CurrentUser.UserId;
            postment.CommentText = CommentText;
            postment.CommentDate = DateTime.Now;

            db.PostComments.Add(postment);
            db.SaveChanges();
            return Json("P");

        }

        catch
        {
            return Json("F");

        }
    }

I have a news project with ment feature. Any one who add a ment can see his ment immediately without reloading the page ( using ajax ). The problem is that when user1 ( for example ) ment on post1 , only user1 can see his ment immediately but all other users need to reload the page to see the ment of user1. How can I solve this problem ?

The code I am using to get the ment :

$(function () {
  $("#AddComment").click(function () {

  var CommentText = document.getElementById("CommetForm").innerHTML;
    var UserName = document.getElementById("UserName").innerHTML;
    var PostId = document.getElementById("PostId").innerHTML;


       $.ajax({
                url: '/PostComment/AddComment',
                type: 'POST',
                dataType: 'json',
                cache: false,
                data: { "PostId": PostId, "CommentText": OrignalCommentText },
                success: function (data)
                {
                    if (data == "P") // Commet Stored on database successfully
                    {
                    document.getElementById("PostComments-" + PostId).innerHTML += 
                    "<li>" +
                                    "<div class='media'>" +
                                        "<div class='media-body'>" +
                                            "<a href='' class='ment-author'>"+UserName+"</a>" +
                                            "<span class='CommetText' id='CommentText-" + PostId + "'>" + CommentText + "</span>" +
                                        "</div>" +
                                    "</div>" +
                                "</li>";

                    }

                    else // Some Error occur during storing database
                    {

                        document.getElementById("CommentError-" + PostId).innerHTML = "\nSomething went wrog, please try agin";

                    }



                }
            });
});
});

And This code for storing ment in database :

  private SocialMediaDatabaseContext db = new SocialMediaDatabaseContext();

  [HttpPost]
    public JsonResult AddComment(string PostId, string CommentText)
    {
        try
        {
            Users CurrentUser = (Users)Session["CurrentUser"];
            PostComment postment = new PostComment();


            CommentText = System.Uri.UnescapeDataString(CommentText);


            postment.PostId = int.Parse(PostId);
            postment.CommentFromId = CurrentUser.UserId;
            postment.CommentText = CommentText;
            postment.CommentDate = DateTime.Now;

            db.PostComments.Add(postment);
            db.SaveChanges();
            return Json("P");

        }

        catch
        {
            return Json("F");

        }
    }
Share Improve this question edited Dec 7, 2014 at 7:14 Erik Funkenbusch 93.5k29 gold badges201 silver badges292 bronze badges asked Dec 6, 2014 at 17:04 Ahmed ShamelAhmed Shamel 1,9624 gold badges28 silver badges62 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 9

I suggest you use SignalR for this. http://www.asp/signalr/overview/getting-started/introduction-to-signalr

TL;DR Use can use setInterval or Websockets to acplish this. Below I explain how.

First of all, we need to understand what is behind this Publish/Subscribe pattern. Since you want to build a real-time application, you may create a function that asks to your server if some data was added since last time it was checked.

USING WindowTimers.setInterval()

Here is the simplest way to acplish this in my point of view, assuming that's your first time and you never worked with websockets before. For instance, in your client-side project you create a function within a setInterval setInterval( checkNewData, time). Your method checkNewData() will make an ajax requisition to your server, asking if some data was added recently:

function checkNewData() {
    // ajax call   
    // On response, if found some new ment, you will inject it in the DOM
}

Then, in your server-side method, get the timestamp of its call and verify in your database if there are some data. Something like this:

// Method written in PHP
public function ajax_checkNewData() {
    $time = time();

    // Asks to your model controller if has something new for us.
    // SELECT ment FROM ments WHERE timestamp > $time
    // Then return its response
}

You will use the response that came from your controller method ajax_checkNewData() to write on your ments-container.

USING WEBSOCKETS (beautiful way)

Now, there are another way to do this, using WebSockets. HTML5 WebSocket represents the first major upgrade in the history of web munications. Before WebSocket, all munication between web clients and servers relied only on HTTP. Now, dynamic data can flow freely over WebSocket connections that are persistent (always on), full duplex (simultaneously bi-directional) and blazingly fast. Amongst different libraries and frameworks, you can use socket.io. I believe this will solve your real-time application problem pretty good, but I am not sure how much of your project you will need to change to suit this solution.

Check it out the simple chat tutorial from SocketIo page and see for yourself if it fits to your needs. Its pretty neat and would be a good challenge to implement using it. Since its event-driven, I believe you wont have problems implementing it.

For further information check it out:

REFERENCES

Get Started: Chat application - http://socket.io/get-started/chat/

Websockets - http://en.wikipedia/wiki/WebSocket

WebSockets - https://developer.mozilla/en/docs/WebSockets

Good luck!

You could write a JavaScript code which makes ajax call to a servlet that checks for updates in the database. Return a flag to the success function of the ajax call and If the state has changed or any ment added to the database, you can reload the page or refresh the consisting of the ments with the new ments.

It's not posting on other pages, because the user1 page is making an AJAX call, so it loads correctly. However, the other pages don't 'know' they are supposed to reload via AJAX. You need some kind of timed loop running that checks for any changes. Either of the above answers should work for it.

You could use SignalR for this, you can send realtime messages to the server, here is a sample to know how to implement SignalR in ASP.NET MVC

https://github./WaleedChayeb/SignalRChatApp

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744357134a4570287.html

相关推荐

  • javascript - Real time insertion of data in mvc - Stack Overflow

    I have a news project with ment feature. Any one who add a ment can see his ment immediately without re

    7天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信