I have an ASP.NET MVC app that opens a "Request" view in a new browser window. When the user submits the form, I'd like the window to close. What should my RequestController code look like to close the window after saving the request information? I'm not sure what the controller action should be returning.
Asked
Active
Viewed 5.3k times
7 Answers
36
You could return a View that has the following javascript (or you could return a JavaScript result) but I prefer the former.
public ActionResult SubmitForm()
{
return View("Close");
}
View for Close:
<body>
<script type="text/javascript">
window.close();
</script>
</body>
Here is a way to do it directly in your Controller but I advise against it
public ActionResult SubmitForm()
{
return JavaScript("window.close();");
}
-
1Curious: why would you advise against the controller-only solution? – gfrizzle May 12 '09 at 16:56
-
5You're manipulating the UI by closing a window. Doesn't seem like a controller responsibility. – womp May 12 '09 at 16:57
-
4I just tried to return the JavaScript and it doesn't work. It only displays "window.close();" on the screen. I read somewhere else that you should call this action using Ajax but I haven't been able to test it. Just giving the heads up. – Aries51 Apr 20 '12 at 13:44
-
9You can't close a window using window.close(). You will get "Scripts may close only the windows that were opened by it." – Toolkit Oct 26 '14 at 06:38
3
Like such:
[HttpPost]
public ActionResult MyController(Model model)
{
//do stuff
ViewBag.Processed = true;
return View();
}
The view:
<%if(null!=ViewBag.Processed && (bool)ViewBag.Processed == true){%>
<script>
window.close();
</script>
<%}%>

Captain Kenpachi
- 6,960
- 7
- 47
- 68
2
This worked for me:
[HttpGet]
public ActionResult Done()
{
return Content(@"<body>
<script type='text/javascript'>
window.close();
</script>
</body> ");
}

Carlos Toledo
- 2,519
- 23
- 23
2
You can close by this code:
return Content(@"<script>window.close();</script>", "text/html");

Glebka
- 1,420
- 3
- 20
- 37
2
It sounds like you could return an almost empty View template that simply had some javascript in the header that just ran "window.close()".

womp
- 115,835
- 26
- 236
- 269
0
This worked for me to close the window.
Controller:
return PartialView("_LoginSuccessPartial");
View:
<script>
var loginwindow = $("#loginWindow").data("kendoWindow");
loginwindow.close();
</script>

Greg Gum
- 33,478
- 39
- 162
- 233
-1
Using this you can close the window like this:
return Content("<script language='javascript'>window.close();</script>");
-
For me, this just returned the script as a string and displayed it, not run it. – Greg Gum Dec 13 '13 at 14:59
-
5