Display a toast notification by making a call from the controller

I am currently utilizing MVC and I am looking to display a message as a toast based on the result of my function from the controller. However, my code seems to be functioning one step behind.

Below is My View:

 @(Html.DevExtreme()
               .Button()
               .Icon("check")
               .Hint("Check the User")
               .OnClick("function(e) {CheckUser(e,data,rowIndex) }")
               )

       function CheckUser(e, f, g) {
           console.log(e)
           console.log(f.InsertedUserId)
           console.log(f.AdminUserId)

           $.ajax({
               type: "POST",
               url: '@Url.Action("CheckUser","UserRoleManagement")',
               data: " {AdminUserId: '" + f.AdminUserId + "', InsertedUserId:'" + f.InsertedUserId + "', IsCSOUser: 'False'}",

               contentType: "application/json; charset=utf-8",
               dataType: "html",
               success: function (result) {
                   var a = '@TempData["CheckerResult"]';
                   if (a.toString() == "Succes") {
                       showToast(e)
                   }
                   else {
                       showToast3(e)
                   }

                   console.log(result);
               }
           })
       };

       function showToast(e) {
           console.log('showToast');

           $("#toast").dxToast({

               message: 'Updated successfully',
               type: 'success',
               displayTime: 3000,
               maxWidth: 500,
               height: "auto",
               animation: { show: { type: 'fade', duration: 400, from: 0, to: 1 }, hide: { type: 'fade', duration: 400, to: 0 } },
               position: { my: 'center bottom', at: 'center bottom', of: window }
           });
           $("#toast").dxToast("show");

       }

       function showToast3(e) {
           console.log('showToast');

           $("#toast").dxToast({

               message: 'Process Failed.',
               type: 'error',
               displayTime: 3000,
               maxWidth: 500,
               height: "auto",
               animation: { show: { type: 'fade', duration: 400, from: 0, to: 1 }, hide: { type: 'fade', duration: 400, to: 0 } },
               position: { my: 'center bottom', at: 'center bottom', of: window }
           });
           $("#toast").dxToast("show");

       }

Here is my Controller:

[HttpPost]
public ActionResult CheckUser(string AdminUserId, string InsertedUserId, bool IsCSOUser)
        {
            RoleGroupRepository rep = new RoleGroupRepository();
            //TempData["Success"] = "User is checked Successfully.";

            SiteSession session = (SiteSession)SessionManager.ReturnSessionObject(SessionKeys.MainSession);

            long CurrentLoggedUserId = session.AdminUserId;

            if (CurrentLoggedUserId == Convert.ToInt64(InsertedUserId))
            {
                TempData["CheckerResult"] = "User check is not Successful.";
                pLogger.INF("User check is not Successful. User can not check by the Inserted User.");
                return Json(new { success = false, responseText = "Fail! User is not checked!" }, JsonRequestBehavior.AllowGet);
            }

            ReturnValuesParser returnValues = rep.CheckUser(AdminUserId, Convert.ToString(CurrentLoggedUserId), IsCSOUser);

            if (returnValues.ReturnCode == 1)
            {
                TempData["CheckerResult"] = "Succes";
                return Json(new { success = true, responseText = "Succes" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                TempData["CheckerResult"] = "User check is not Successful.";
                pLogger.INF("User check is not Successful" + returnValues.returnDescription_En);
            }

            return Json(new { success = false, responseText = "Fail! User is not checked!" }, JsonRequestBehavior.AllowGet);
        }

How can I adjust this to display my message based on the TempData["CheckerResult"] result correctly? It appears to always be referencing one step behind. While I understand the issue logically, I'm unsure how to resolve it.

I would appreciate any guidance or insights. Thank you!

Answer №1

Upon inspecting the original value displayed during the initial view rendering, you are presented with:

var a = '@TempData["CheckerResult"]';

However, no data from the AJAX call response is being utilized:

result

By examining the page source in your browser, it becomes evident that @TempData["CheckerResult"] essentially transforms into a static literal value within your JavaScript code. This value will not dynamically change.

In essence, refrain from utilizing TempData when not returning a view but instead JSON, which carries the desired information:

return Json(new { success = true, responseText = "Success" }, JsonRequestBehavior.AllowGet);

Hence, analyze this returned data within your AJAX response handler:

if (result.responseText == "Success")

In addition, it is recommended to modify this section:

dataType: "html"

to read as follows:

dataType: "json"

This adjustment is necessary given that the server is expected to return JSON, not HTML content.

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

Using jQuery to make an asynchronous request for a large file can cause the browser to become

After initiating a jQuery $.get request to retrieve data from an HTML file, I have utilized the success function to filter out a select element's options and present them as paragraphs within div elements that are subsequently appended to my markup. A ...

Tips for dynamically passing a string into a Javascript function

Here is a JavaScript function that I have: function doIt(link) { alert(link); } I am using this function in the following JavaScript code snippet. Here, I am dynamically creating an anchor tag and appending it to my HTML page: jQuery.each(data, func ...

`user implemented object comparison within a set in unity (es6)`

I am facing an issue where I need to handle multiple values and ensure that only unique ones are used. With the use of node js and access to harmony collections through the --harmony flag, I have considered using a Set as a potential solution. What I am s ...

Using jQuery to submit a form and update values

I am currently working with a datatable that includes a detail column with an edit button. Upon clicking the edit button, I pass the ID as a parameter and fetch all the values associated with that ID to display in a form. However, when I edit the values an ...

Take users to another page upon form submission

I'm working on a React form using Typescript and Material-UI. Here's an example: import React, { useState } from "react"; import TextField from "@material-ui/core/TextField"; import { createStyles, makeStyles, Theme } from &qu ...

The TipTap Editor does not properly register spaces

In our project, we are utilizing the TipTap rich text editor. However, we are encountering an issue where spaces are not being recognized correctly - a space is only created after every 2 clicks. Our framework of choice is Vue.JS. import { Editor, EditorC ...

Set the height of the vertical scroll at a fixed 100% floatValue

Check out my creation at http://jsfiddle.net/ZygnV/ html, body { margin: 0; padding: 0; height: 100%; } .main-content-wrapper { height: 100%; overflow-y: hidden; white-space: nowrap; } .main-sidebar { display: inline-block; height: 1 ...

Reacting with Node.js: Capturing a selected option from a dropdown menu and storing it in the database

On my React frontend, I have a select dropdown like this: <select name="level" value={level} onChange={this.handleChange} className="form-control"> <option>Begineer</option> <option>Intermediate</option> <option> ...

ActiveX cannot be executed from the server

My MFC activeX control works fine when run from disk, but I encounter errors when hosting it on a server. Client: Windows 7 machine Server: Ubuntu running Apache Below is the HTML code along with the encountered errors. Any advice would be much ap ...

Leveraging a nodejs script integrated with socket.io within an angular/electron hybrid application

I have successfully created an electron/angular app that is functioning well. Additionally, I have developed a nodejs script to open a socket.io server using typescript + webpack to generate all files in a bundled js file. My challenge arises when trying ...

Oops! SAPUI5 is encountering an issue with reading property '0' of undefined

Is there a possibility of encountering multiple errors leading to this specific error message? https://i.stack.imgur.com/RpWhw.png Despite searching online, it appears that the error occurs in the JavaScript file when getelementbyid returns null. However ...

Transferring information between two independent React applications

I am facing a challenge with an HTML page that is incorporating two separate webpack-generated React bundles. Each bundle has its own index.js entry file, which simply executes a RenderDOM.render() of its corresponding component to its designated <div&g ...

Determine the latest date within each group and display the corresponding output value

I am seeking a way to showcase only the most recent value for each group. For example, in the CSV data provided below, the total amount of Bagels in the Cinnamon Raisin variety were collected during three different sampling periods: May 2017, March 2017, ...

Express is capable of dynamically modifying routes at runtime

I've set up an express server with my index.js looking like this: let some_parameter = some_value; const configuredHandler = new Handler(some_parameter); const server = express(); server .get("*", configuredHandler.handleRequest) .post("*", ...

Log records for forms authentication timeouts

I am looking for a way to detect when an asp.net Form Authentication ticket expires so that I can log the user who was signed out due to inactivity on the server. Is there an event that triggers on the server when the authentication ticket expires? <se ...

Make sure to declare rest parameters first when using Typescript

I am dealing with a function that takes in multiple string arguments and one final argument of a complex type, which is called Expression. This particular code looks like this in JavaScript: function layerProp(...args) { const fields = args.slice(0, -1) ...

Is there a way to enable scrolling on the page upon loading, without moving the embedded PDF object itself?

After embedding a PDF object on my webpage, I noticed that when loading the page and scrolling using the mouse wheel, it actually scrolls up and down inside the PDF instead of moving through the entire page. To fix this issue, I have to first click in a bl ...

Error encountered when sending AJAX post request to web server due to exceeding size limit

I encountered an error when attempting to post a base64 string: System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializerserializer,Stringinput,Typetype,Int32depthLimit) The JSON data includes base64 information and some details ...

reviewing the content of an element upon mouse hover

I'm having trouble setting up a mouse enter event that should trigger if the element contains specific text. However, for some reason, it seems like the :contains parameter is not being recognized. Here is the HTML: <div class="sample">red< ...

What are the steps involved in manipulating objects within an asynchronous result object?

I'm interested in learning how to manipulate a JS object from one file into another asynchronously, as my experience with asynchronous code principles is limited. Scenario: In my app.js file, I dynamically generate 'app panels' based on ...