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
?
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.
在显示如下所示的警报消息后,尝试使用 'window.location.href' javascript 对象重定向到主页,
return Content("<script language='javascript' type='text/javascript'>alert('Thanks for Feedback!');window.location.href='/';</script>");
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.