Exploring the Power of Integrating SignalR 2 with a Database

After going through a tutorial on creating a basic messaging web application using SignalR and MVC, I realized that the tutorial did not cover how to store messages in a database or display previous messages to users. The main code snippet from the tutorial looks like 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>

...

With an EF Code-first setup where there is a Comment class defined as:

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

And a corresponding Comment controller with a Create method:

public ActionResult Create([Bind(Include = "CommentID, UserName, CommentText")] Comment comment)
{
    if (ModelState.IsValid)
    {
        db.Comments.Add(comment);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(comment);
}

I understand that I need to incorporate AJAX functionality to fetch and post messages to the database. However, I am unsure about how to go about it. Can someone guide me on writing the necessary AJAX queries to achieve this? Any help or suggestions would be greatly appreciated. Thank you.

Answer №1

No additional controller is required for managing messages in the ChatHub class. Simply store messages in the ChatHub.Send method and present previous messages to new users by customizing the ChatHub.OnConnected hub event - invoke addNewMessageToPage for newly connected users.

public class ChatHub : Hub
{
    public void Send(string name, string message)
    {
        // Trigger the addNewMessageToPage method to notify clients.
        Clients.All.addNewMessageToPage(name, message);

        var comment = new Comment
        {
            CommentID = Guid.NewGuid(), // or implement an autoincrement for an int 
            UserName = name,
            CommentText = message
        }
        db.Comments.Add(comment); 
        db.SaveChanges();
    }

    public override Task OnConnected()
    {
        var comments = db.Comments.ToList(); // consider implementing some form of caching here
        foreach(var comment in comments)
        {
            Clients.Client(Context.ConnectionID).addNewMessageToPage(comment.UserName, comment.CommentText);
        }
        return base.OnConnected();
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determining the clicked node in a JavaScript environment

There are multiple spans with labels. <span class="viewEdit">View and edit class one.</span> <span class="viewEdit">View and edit class two.</span> <span class="viewEdit">View and edit class three.</span> <span clas ...

Determine if the user's request to my website is made through a URL visit or a script src/link href request

Presently, I am working on developing a custom tool similar to Rawgit, as a backup in case Rawgit goes down. Below is the PHP code I have created: <?php $urlquery = $_SERVER['QUERY_STRING']; $fullurl = 'http://' . $_SERVER['SE ...

Is there a way to use a specific keyboard input to alter the characteristics of shapes on my webpage?

Is there a way to change certain attributes of a shape onscreen when a specific key is pressed by the user? For example, can I make it so that pressing "a" changes the color of the shape? I attempted to modify a mouse rollover event to work with the desir ...

A guide on transforming a string into an array of objects using Node.js

Hey everyone, I have a single string that I need to convert into an array of objects in Node.js. let result = ""[{'path': '/home/media/fileyear.jpg', 'vectors': [0.1234, 0.457, 0.234]}, {'path': '/home/med ...

finding the node version in a code repository

Is it possible to determine the targeted node version (4 or 6) of a Node.js application by examining its code? I'm currently reviewing this: https://github.com/jorditost/node-postgres-restapi ...

Invoking a JavaScript function within a different JavaScript function

Is there a way to ensure that the JavaScript function works properly even when using a text editor? var editor = $('#CKEditor1').ckeditorGet(); editor.on("instanceReady", function () { this.document.on("keydown", function (event) { ...

Setting a user as authenticated and logged in .NET core

If I'm utilizing Identity (core), is it possible to programmatically designate a logged-in user? Our application necessitates the option for users to log in either through standard Identity (using email and password) or by utilizing provided AD infor ...

What is a more efficient way to write nested subscribe in Angular?

I am a beginner with RxJS and I'm interested in learning how to write clean code using it. I currently have a nested subscription that I've been trying to refactor without success. firstMethod() { this.testMethod(name) console.log(this.curren ...

RxJs will only consider the initial occurrence of a specific type of value and ignore any subsequent occurrences until a different type of value is encountered

I'm faced with a situation where I need to extract the first occurrence of a specific value type, followed by the next unique value of a different type. Let's break it down with an example: of(1,1,1,1,2,3,4) .pipe( // some operators ) .subsc ...

Is it not possible to utilize inline "if" statements in conjunction with useEffect within a functional React component?

I'm currently working on integrating Okta's React SDK into a TypeScript-based application using functional components instead of class-based ones. My main challenge lies in rendering a part of the app's menu based on the user's authenti ...

Learn the best way to populate Google Map popup windows with multiple values and include a button to pass unique ID values

I'm facing an issue with my code. When I click on a marker, it should display "Madivala, 12.914494, 77.560381,car,as12" along with a button to pass ID values. Can someone help me figure out how to move forward? http://jsfiddle.net/cLADs/123/ <ht ...

The background image is not appearing on the div as expected

I've been attempting to create a div and set a background image for it using jQuery, but I seem to be facing issues. When I try setting the background color to white, it works fine. Here's the code snippet: function appendToDom(poster) { ...

"Jest test.each is throwing errors due to improper data types

Currently, I am utilizing Jest#test.each to execute some unit tests. Below is the code snippet: const invalidTestCases = [ [null, TypeError], [undefined, TypeError], [false, TypeError], [true, TypeError], ]; describe('normalizeNames', ...

Having trouble escaping single quotes in JSON.stringify when using a replacer function

I'm attempting to replace single quotation marks in the values of my JSON string with \' however, it seems to not be working when I try to use the replacer function. var myObj = { test: "'p'" } var re ...

Listen for a click event on an Unordered List using addEventListener

Struggling to transform a for loop that iterates through an unordered list of hyperlinks and adds an 'onclick' function to each into one using an event listener instead. Unfortunately, I have not been able to create a functional solution. Below ...

SQL - Retrieve information for a specified time frame using a predetermined value

I am looking to retrieve data from a table, extract the information using JavaScript, and visualize it on a graph where the x-axis represents dates and the y-axis represents numbers. The DATA table is structured as follows (please note that attempts to fo ...

Leveraging Environment Variables in Separate JavaScript Files within a Node Express Application

After trying various methods and searching extensively online, I am struggling to use environment variables in a separate JavaScript file within an Express App. My Setup: In my Express app, I have an index.js file that serves an HTML page with associated ...

"Connection Failure: MongoDB Server Unreachable"`

I've been working on a basic web application using MongoDB, Express, and NodeJS. Unfortunately, I've encountered an issue where I cannot connect to MongoDB and keep receiving the following error message in the terminal: (node:28265) UnhandledPro ...

ERROR: Module 're2' not found in './build/Release/re2' (npm)

After receiving suggestions from sonarQube, I am attempting to switch out my original regular expression with RE2. However, upon installation, the following error message appears: Error: Cannot locate module './build/Release/re2' Important note ...

Generate a unique identifier and verify its presence within an array of objects

Is there a way to generate a unique identifier and add it to an object in an array, only if the id does not already exist in any other objects within the array? Within the React code snippet provided below, the "saveColor" function was intended to accompl ...