locked
Connecting SignalR with a database RRS feed

  • Question

  • User-1204785697 posted

    I have followed this tutorial and learned a simple messaging web application. This tutorial doesn't show anything about how to add messages to database and show previous messages to the users. The core code in the tutorial is this :

    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion">
        </ul>
    </div>
    @section scripts {
    
        <script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script>
        <script src="~/signalr/hubs"></script>
        <script>
            $(function () {
                var chat = $.connection.chatHub;
                chat.client.addNewMessageToPage = function (name, message) {
                    $('#discussion').append('<li><strong>' + htmlEncode(name) 
                        + '</strong>: ' + htmlEncode(message) + '</li>');
                };
                $('#displayname').val(prompt('Enter your name:', ''));
                $('#message').focus();
                $.connection.hub.start().done(function () {
                    $('#sendmessage').click(function () {
                        chat.server.send($('#displayname').val(), $('#message').val());
                        $('#message').val('').focus();
                    });
                });
            });
            function htmlEncode(value) {
                var encodedValue = $('<div />').text(value).html();
                return encodedValue;
            }
        </script>
    }

    If I'm using EF Code-first and I have a Comment class like this :

     public class Comment
        {
            public int CommentID { get; set; }
            public string CommentText { get; set; }
        }

    How can I edit that JavaScript code to show previous messages and how can I write new messages to the database? Any help or hints are welcome. Thanks.

    Sunday, December 20, 2015 12:28 PM

Answers

  • User-369506445 posted

    ok , i put  here a sample , that per 3sec fetch last data

    first create a webform in your Root project called AjaxForm.aspx

     protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            [WebMethod]
            public static List<Comment> GetLastComment()
            {
                // I create a sample list 
                var list = new List<Comment>
                {
                    new Comment()
                    {
                        CommentID = 1,
                        CommentText = "comment 1"
                    },
                    new Comment()
                    {
                        CommentID = 1,
                        CommentText = "comment 2"
                    }
                };
    
                ////  you can use below query for return our data
                //using (var context=new yourContext())
                //{
                //    return context.Comment.ToList();
                //}
           
                return list;
            }

    now in main form add under your last script , below script :

     <script>
            $(function () {
                setInterval(function () {
                    myFunc();
                }, 3000);
            });
    
            var myFunc = function LastComment() {
                $.ajax({
                    url: "AjaxForm.aspx/GetLastComment",
                    type: 'POST',
                    data: {},
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    success: function (response, status) {
                        var list = response.d;
                        $.each(list, function (index, obj) {
                            $('#discussion').append('<li><strong>' + obj.CommentID
                                            + '</strong>:&nbsp;&nbsp;' + obj.CommentText + '</li>');
    
                        });
                    },
                    error: function () {
                        alert("Oops! It's an Error");
                    }
                });
            };
        </script>

    that code call the GetLastComment method from code behind and you can change it and put your code or anythings

    note, it's a sample , and you can change it and custom better it

    for example you can call  function LastComment() when your user login for first , and define boolean variable for is duplicate or isn't duplicate

    i hope it can be helpful

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 21, 2015 5:52 AM

All replies

  • User-369506445 posted

    hi

    in your project you have a folder called Hubs and have a class called ChatHub.cs

    put below code :

    public void Send(string name, string message)
            {
                // Call the addNewMessageToPage method to update clients.
                Clients.All.addNewMessageToPage(name, message);
                using (var context = new yourContextClass())
                {
                    Comment obj=new Comment();
                    obj.CommentID = 1;
                    obj.CommentText = message;
                    context.Comment.Add(obj);
                    context.SaveChange();
                }
            }

    Sunday, December 20, 2015 1:09 PM
  • User-1204785697 posted

    Thank you very much.

    Can you tell me how I can list previous messages on that page?

    Thanks.

    Sunday, December 20, 2015 1:16 PM
  • User-369506445 posted

    you can write a Ajax method and call last comments form database

    for example in below code :

       $('#sendmessage').click(function () {
     /here write a ajax script

    and when get result use below script :

    $('#discussion').append('<li><strong>' + htmlEncode(name) 
                        + '</strong>: ' + htmlEncode(message) + '</li>');

    that is a sample , you can use the Ajax method to other place or use a interval timer for read them

    Sunday, December 20, 2015 1:33 PM
  • User-1204785697 posted

    Can you be more explanatory please? Can you tell me what ajax script look like? Thanks.

    Sunday, December 20, 2015 3:23 PM
  • User-369506445 posted

    ok , i put  here a sample , that per 3sec fetch last data

    first create a webform in your Root project called AjaxForm.aspx

     protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            [WebMethod]
            public static List<Comment> GetLastComment()
            {
                // I create a sample list 
                var list = new List<Comment>
                {
                    new Comment()
                    {
                        CommentID = 1,
                        CommentText = "comment 1"
                    },
                    new Comment()
                    {
                        CommentID = 1,
                        CommentText = "comment 2"
                    }
                };
    
                ////  you can use below query for return our data
                //using (var context=new yourContext())
                //{
                //    return context.Comment.ToList();
                //}
           
                return list;
            }

    now in main form add under your last script , below script :

     <script>
            $(function () {
                setInterval(function () {
                    myFunc();
                }, 3000);
            });
    
            var myFunc = function LastComment() {
                $.ajax({
                    url: "AjaxForm.aspx/GetLastComment",
                    type: 'POST',
                    data: {},
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    success: function (response, status) {
                        var list = response.d;
                        $.each(list, function (index, obj) {
                            $('#discussion').append('<li><strong>' + obj.CommentID
                                            + '</strong>:&nbsp;&nbsp;' + obj.CommentText + '</li>');
    
                        });
                    },
                    error: function () {
                        alert("Oops! It's an Error");
                    }
                });
            };
        </script>

    that code call the GetLastComment method from code behind and you can change it and put your code or anythings

    note, it's a sample , and you can change it and custom better it

    for example you can call  function LastComment() when your user login for first , and define boolean variable for is duplicate or isn't duplicate

    i hope it can be helpful

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 21, 2015 5:52 AM