1

I want to display alert message and redirect to the home page in controller.

The code for Create action is:

if (ModelState.IsValid)
{
    _context.Add(contact);
    await _context.SaveChangesAsync();
    

    return Content("<script language='javascript' type='text/javascript'>alert('Thanks for Feedback!');</script>");
   
}
return View(contact);

But I wanted to use the return RedirectToAction because it should redirect the user to the specific page in the final execution of code, so how do I replace the return content to redirect to Index page of HomeController?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
lol
  • 53
  • 1
  • 6

2 Answers2

3

You can use TempData to store the message and then run the alert on the home page index view

In the controller

TempData["message"] = "Thanks for Feedback!";
return RedirectToAction("Index","Home");

In Index View (home)

@if (TempData["message"] != null)
{
    <script>alert('@TempData["message"]');</script>
}

The TempData will persist for the redirect, but after another page load, it will not be present.

Ben D
  • 669
  • 1
  • 11
  • 19
  • 1
    Thanks, it works. But when i go to the home page again it will appear the message again. Like when u go to another page and back to the index page. The message will still show – lol Sep 11 '20 at 14:16
  • @lol have a look at this post, very useful to know the difference and they will come in handy at some point I'm sure. I speak from experience - https://stackoverflow.com/questions/7993263/viewbag-viewdata-and-tempdata – Ben D Sep 11 '20 at 14:21
  • @lol if you set it up correctly, it should only appear once, then when you go back to the home page (another HTTP request) it should empty the TempData value and not appear – Ben D Sep 11 '20 at 14:23
0

Try 'window.location.href' javascript object to redirect to home page after displaying alert message as shown below,

return Content("<script language='javascript' type='text/javascript'>alert('Thanks for Feedback!');window.location.href='/';</script>");