How to close browser window using Asp.Net MVC and JavaScript
Answers (2)
Add AnswerTo close the browser window using ASP.NET MVC and JavaScript, you can use the window.close()
method. Here are the steps:
- Define an action in the controller: Define an action in the controller that returns a view that contains the JavaScript code to close the window.
For example:
public ActionResult CloseWindow() { return View(); }
- Create a view with JavaScript code: Create a view that contains the JavaScript code to close the window.
For example:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Close Window</title> </head> <body> <script> window.close(); </script> </body> </html>
In this example, the window.close()
method is called in a script block. When the view is loaded, the script will execute and close the window.
- Call the action from a link or a button: Call the
CloseWindow
action from a link or a button on the page.
For example:
<a href="@Url.Action("CloseWindow", "MyController")">Close Window</a>
In this example, the Url.Action()
method is used to generate the URL for the CloseWindow
action. When the link is clicked, the CloseWindow
action will be executed and the view with the JavaScript code to close the window will be returned and executed.
Note: In some browsers, the window.close()
method can only be called from a window that was opened by a script. If the window was not opened by a script, the method may not work. Additionally, some browsers may prompt the user before closing the window.