Is there a way to ensure my chat view functions properly without relying on partial views?

I am currently working on integrating a private chat feature using SignalR in my project, and I have encountered an issue while creating a View with accessible model values to pass to the server. Specifically, I have a list of doctors, and when a user clicks on a doctor's link, it should open a chat partial view for consultation. However, I am facing difficulties in utilizing the model's values from the partial view in the parent view's JavaScript code. Although there are suggestions on how to retrieve data from a partial view on Stack Overflow, I have also attempted to write JavaScript within the partial view using @section, but this approach is not permitted. As a solution, I am considering combining both models into one and using it in the parent view. For instance, when I click on a doctor's name, I want to update the values in the chatbox specific to that doctor and use those values in the JavaScript for chatting. Here is some of my Parent View code:

@model E_HealthCare_Web.ViewModels.ConsultationViewModel

<section class="chat-wrapper">
    <!-- Code for doctor list goes here -->
</section>
<section class="chatbox-section">
    <!-- Chatbox section code goes here -->
</section>

Below is the partial view where I'm trying to access the model values:

@model E_HealthCare_Web.ViewModels.ChatLoadViewModel

<!-- Partial view content here -->

Lastly, here is the JavaScript responsible for the chat functionality:

 // JavaScript code for chat functionality goes here 

Additionally, below are some controller methods and model classes used in this implementation:

//Controller methods and model classes code goes here

If anyone has suggestions or guidance on how to improve this implementation, please feel free to share your insights. Thank you!

Answer №1

Utilizing session data can be beneficial as it allows for the storage of information needed across multiple actions/views. Keep in mind that session data is stored on the server, so if you intend to access it from JavaScript, an Ajax request will be necessary. (Are you planning to use the data passed from a partial view in JS? Or is there some confusion here?)

To implement this, create two actions within your Home controller: one to add data to the session and another to retrieve the saved data.

public IActionResult SetChatData(object data)
{            
    Session["chatData"] = data;
    return Json(data);
}

public IActionResult GetChatData()
{
    return Json(Session["chatData"]);
}

You can now utilize these methods to write or retrieve data from the session by sending an Ajax request:

// This function should return the provided data parameter
function setChatData(data) {
    var result;

    $.ajax({
        url: "/Home/SetChatData",
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify({ data: data }),
        contentType: 'application/json; charset=utf-8',
        async: false
    }).done(function(data) {
        result = data;
    });

    return result;
}

The following request fetches data:

function getChatData() {
    var result;

    $.ajax({
        url: "/Home/GetChatData",
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        async: false
    }).done(function(data) {
        result = data;
    });

    return result;
}

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

Problem: The variable "$" is not defined in angular datatables causing a ReferenceError

Trying to implement Paging and sorting in my table, but encountered an error even after following all the steps mentioned here: . Tried troubleshooting the issue with no success. Ensured that all dependencies were installed properly. Below is the compo ...

How to perfectly center a dropdown menu using CSS across different web browsers

I am dealing with a dropdown menu that is auto-generated by WordPress, so altering the HTML structure is not an option. However, I have the flexibility to adjust the CSS styling to correct an alignment issue in my dropdown menu. Currently, I'm facing ...

Despite utilizing overflow and wrap properties, HTML lists still fail to display horizontally

Make sure to copy the code and run the HTML file first. For organization, place the JavaScript file in the scripts folder and the CSS file in the styles folder. The issue at hand is that the li elements are not displaying horizontally as intended; they n ...

When working with styled components, how can I effectively apply different styles using two layers of class names within the component declaration?

In my next.js project, I have developed a Container component with specific styles. As I incorporate this container component throughout the site, I aim to assign it a className for context-based styling. Illustrated below is an example of the Container c ...

Errors encountered by the Chrome extension

Hey there, I've recently delved into creating a chrome extension but hit a roadblock. My issue revolves around the service worker registration failing and encountering errors related to undefined properties. https://i.stack.imgur.com/bGzB4.png The c ...

What could be causing the response data from an AJAX request to be in error instead of success?

My JSON data is securely stored on , and I can access it through a unique URL. Here is the specific URL: The JSON data found at the above URL is: { "glossary": { "title": "Suyog", "GlossDiv": { ...

Craft dynamic SVG components using TypeScript

Looking to generate a correctly formatted SVG element using TypeScript: createSVGElement(tag) { return document.createElementNS("http://www.w3.org/2000/svg", tag); } Encountering an issue with tslint: Error message: 'Forbidden http url in str ...

Ways to move to the next line following the navigation bar text

Below is the code snippet that I am working with: <nav class="navbar navbar-expand-sm navbar-dark "> <div class="container-fluid"> <a class="navbar-brand" href="#">LOREM IPSUM</a&g ...

Ways to check for child items in a JSON object

My Angular-built menu uses JSON and spans up to 3 levels deep. Some items have no children, while others go further down the hierarchy. I'm trying to determine if a selected subcategory has child elements in order to hide a button. Each time a subcat ...

Error: Identical div IDs detected

<div id="tagTree1" class="span-6 border" style='width:280px;height:400px;overflow:auto;float:left;margin:10px; '> <a class="tabheader" style="font-size:large">Data Type</a><br /> <div class="pane">Refine sea ...

Tips for converting an entire column along the vertical axis to a different language

Looking for a solution with my grid view where I want to translate the items of the second column on the y axis, as shown in the image. I attempted to use the translateY() function, but it resulted in the need to scroll in order to see the translated items ...

Generate a fresh JSON object following a click event triggered by an HTTP PUT request

I have the following structure in JSON format: "disputes": [ { id: "", negotiation_type: "", history:{ user_flag: "", created_at: "", updated_at: "", created_by: null, updated_by: null, ...

Changing class in jQuery ignores CSS style

I have a id="header" div that initially has css rule: padding: 25px 0;. I want to decrease the padding of this div when scrolling down the page. $(document).ready(function() { var headerID = $("#header"); $(this).scroll(function() { if (!$(this).s ...

Wait for Axios Request Interceptor to complete before sending another ajax call

One feature I have added is a request interceptor for all axios calls. This interceptor checks the JWT token and automatically refreshes it if necessary. axios.interceptors.request.use((config) =>{ const currentState = store.getState(); // get upd ...

Customizing AngularJS Scripts to Include Target Blank

I'm feeling a bit lost. I need to include a target="_blank" on my anchor link. The issue is that the anchor tag is linked to a script in angular. I am not familiar with this JavaScript framework. I have tried searching through the documentation for po ...

How to Send Javascript DOM Value to Inner HTML

I am trying to extract a value from a hidden element ID and set it as the inner HTML for another element ID. Below is my code: <script> function replaceText(){ var x=document.getElementById("mainTitle1").textContent; document.getElementById("mainTi ...

The struggle of positioning two divs in alignment

In my HTML code, I have a div container named row3red3. Inside this container, there are two divs: left (.row3red3slika) and right (.row3red3info). I am facing an issue where I cannot position the right div .row3red3info on top, inline after the image. I ...

Can an array be generated on-the-fly with objects contained within it?

Seeking advice on looping through an array of objects to achieve a specific result. Here is the initial array: var testArray = [{'name':'name1', 'xaxis':'xaxis1', 'yaxis':'yaxis1'}, ...

Listening to React events on multiple elements in an array

When my React render function is running, it ends up rendering a group of elements: data.map((element) => { return <Object onChange={this.onObjectChange} />; }); I'm wondering, what is the best approach to determine which specific object ...

While it is possible to filter by friend.brand.id within friends in Angular, unfortunately the || undefined trick cannot be used to reset the filter when it is NULL

In the futuristic world of 2075, immortal humans have subjugated mortal humans. There exists a unique store where mortal friends are sold, and efforts are being made to develop an app that allows customers to manage their friends based on their favorite br ...