简体   繁体   中英

How to use message box in MVC controller?

I've created a MVC application. User has to register and once it is completed, I'm redirecting him to "thank you" page. However I would like just to show user a pop-up with this message. How can I achieve this?

My code:

[HttpPost]
public ActionResult Enquiry(Enquiry enquiry)
{
    if (ModelState.IsValid)
    {
        dbEntities.Enquiries.AddObject(enquiry);
        dbEntities.SaveChanges();
        enquiry.SendEnquiryEmail(enquiry);

        return RedirectToAction("Thankyou"); 
    }

    return View(enquiry);
}

//redirect to thankyou page
public ActionResult Thankyou()
{
    return View();
}

To ensure your 'alert' in your view only shows up when you intend (a redirect from your ThankYou method) and not when somebody accidentally navigates to your 'ThankYou' view

//redirect to thankyou page
public ActionResult Thankyou()
{
    TempData["alertMessage"] = "Whatever you want to alert the user with";
    return View();
}

Then in your "ThankYou" view, this:

   if(null != TempData["alertMessage"])
   {
      <script type="text/javascript">
       alert("@TempData[alertMessage]");
      </script>
   }

This will write out the script as you normally would for any JavaScript. Hope this helps!

in controller use this code

public ActionResult Edit(CoverLetterModel model)
{
    TempData["msg"] = "<script>alert('Change succesfully');</script>";
}

in view use this code

@Html.Raw(TempData["msg"])

@Reynolds

Your answer is perfect.

In Razor, the following line can be replaced

alert("@TempData[alertMessage]");

by the following

alert('@TempData["alertMessage"]');

PS. Notice the quotes

It sounds like you may want to display the "thank you" message box on the view where the user enters the registration data?

If this is the case, you need to AJAX POST to an action, then handle the success/fail message that returns from the action in your client side javascript.

One thing to keep in mind if you do this is you don't want your users to click the "submit" button multiple times so you may want to hide or disable it after the first click and show/enable it on a validation error...

On the web you will need to use Javascript to display a message box. The syntax (To go into your view is in it's simplest form)

Alert("Hello There!");

You cannot call this directly from your controller. Simply put the above code into your ThankYou view.

This is very simply but should give you the concept.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM