Displaying an alert box once the form has been submitted

I have created a form in asp.net mvc and I am looking to display an alert message when the user submits the form.

public ActionResult AddMessage(Message message)
{
       If(ModelState.IsValid) 
       {
                db.Messages.Add(message);
                db.SaveChanges();
                return RedirectToAction(“Index”);
       }
       else
       {
                return View();
       }
}

Answer №1

The function known as alert in JavaScript must be run on the client side, specifically by the browser.

If you are submitting a standard form and wish to display an alert when the ModelState.IsValid condition is met, you must include this within the view returned by the index action.

To transmit data between your current action method code and the action method/view generated by a redirect response, you can utilize TempData.

public ActionResult AddMessage(Message message)
{
    If(ModelState.IsValid) 
    {
        db.Messages.Add(message);
        db.SaveChanges();
        TempData["Message"] = "Saved successfully";
        return RedirectToAction(“Index”);
    }
    else
    {
        return View();
    }
}

In the view produced by the Index action, you can verify the presence of TempData["Message"], retrieve it if present, and display it using an alert.

@section Scripts
{
  <script>
         @if(TempData["Message"]!=null)
         {
              @:alert("@TempData["Message"]");
         }  
  </script>
}

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

Convert AngularJS ng-repeat data received from Laravel API into a specific format

My Backend API is built on Laravel 5.2 and the Frontend uses AngularJS. During a Laravel validation process, I check for errors and return an error message if validation fails. However, when I display these errors on the frontend, they appear in the forma ...

Displaying an undefined value using ExpressJs (to present an [object])

While learning expressjs, I encountered an issue where the value I passed did not appear in the output. I created a new Routes file and defined a function with Route methods in it. However, when I set Route paths, the value did not show up in the output. A ...

I am interested in transmitting a variety of information from a form to a database

Would it be possible for me to send a message with just my name? Any help would be greatly appreciated. (https://i.sstatic.net/ZvF8F.png) ...

The function of hasClass within an if statement appears to be malfunctioning

I'm struggling to figure out why my .hasClass function is not functioning correctly. I've implemented the Quick Search jQuery plugin, and below is the code I am using: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.mi ...

the class-based component fails to update when there is a change in the React Router route

I'm new to using class components in React and I have a question regarding react-router and lifecycle methods. In my app, I'm displaying products in a component and switching between categories of products by filtering as the API doesn't pro ...

How can you retrieve input radio button values using javascript or ajax and display or hide a button accordingly?

I've created a form that includes radio input buttons and a textarea field as follows: <input type="radio" value="2" id="order_status"> Review <input type="radio" value="1" id="order_status"> Accept <input type="radio" value="2" id="or ...

Deploying an Angular 2 application using SystemJS and Gulp can sometimes feel cumbersome due to its

Although I have experience developing with Angular, I recently started working with Angular 2. After completing the quickstarter tutorial, I attempted to deploy the finished application on a server in production mode. My lack of experience with SystemJS a ...

Guide for configuring a server to exclusively render Vue components

I have been utilizing the vue-no-ssr library (available at https://github.com/egoist/vue-no-ssr), but it only renders components on the client side. I require my component to render on the server side. Is there a method to create a vue component that exclu ...

What could be the reason for the malfunctioning of my JavaScript code?

I have obtained some code from a tutorial on coding website called JSFiddle $(function() { $('.toggler').click(function() { $(this).find('div').slideToggle(); }); }); <div class="toggler"> This is the title < ...

How are resolve and reject utilized within JavaScript Promises?

Initially, I believed that resolve simply passes the parameter to the function in then, so I conducted this experiment: const promise = new Promise((resolve, reject) => { resolve(new Promise(resolve => resolve(2333))) }) // promise.then(innerPromi ...

Use jQuery to duplicate an image that has the "active" class, then assign it as the background image for a div element

I am utilizing the default carousel from Twitter Bootstrap to create a basic slider. What I aim to do is, when an item becomes active, the image inside that item should be duplicated and set as the background image for the div with the 'testimonials-b ...

Maintaining binding while appending inner elements within a container using jQuery

I'm struggling to transfer the contents of one container to another without losing any bindings, and it's proving quite tricky! <div class="container"> <div class="field"> <label>Username</label> < ...

JavaScript SQL results in either a string or an object after executing a

I am facing an issue with the following query: sql = client.query("SELECT * FROM monitormaterialsept", function (err, result, fields) { if (err) throw err; console.log(result); }) I am unsure of what the output of the sql variable is. Is there a ...

Tips for locating the previous CSS value before it was altered by javascript code

I am working on adjusting the CSS variables provided by the system using JavaScript with the following code: document.body.style.setProperty("--rh__primary-base", "rgba(254,80,0)"); However, when I inspect the element, I can see that t ...

What causes Express Async Errors to produce unexpected outcomes?

I stumbled upon a fantastic npm package called Express Async Errors that is highly recommended in the documentation. However, when I try to implement it, my server crashes. Here is my Route handler code: Controller const { Genre } = require("../models"); ...

Watch the Newest Vimeo Showcase Reel

I have a new project where my client is requesting to display the latest video from a specific Vimeo Portfolio. I already have a script that can fetch the latest video from the entire account using JavaScript as shown below: http://codepen.io/buschschwick ...

`There is a lack of props validation in the react/prop-types``

As I set up my Next-React app on Netlify, I encountered an error in the deploy log: Netlify deploy log indicates: "Error: 'Component' is missing in props validation", "Error: 'pageProps' is missing in props validation" within my ./page ...

Creating an animated transition for an element's height with CSS

I need to animate the height of a div that doesn't have a specified height. Using max-height isn't an option due to multiple potential height amounts. I attempted adding transition: height 0.2s ease to the div, but it didn't work as expecte ...

Using window.print as a direct jQuery callback is considered an illegal invocation

Curious about the behavior when using Chrome $(selector).click(window.print) results in an 'illegal invocation' error $(selector).click(function() { window.print(); }), on the other hand, works without any issues To see a demo, visit http://js ...

The Vue EventBus does not support passing object attributes

Looking for assistance with integrating two Vue single page components. The 'Searchbar' component features a dialog box where users input data. This data is required in the 'ResultList' component for further processing. To achieve this ...