ASP.NET MVC: How to close browser window instead of returning a view?
I have an instance where, not by my own choice, but I have a secondary popup window in the browser. Upon form submission back to a server-side MVC method, after this method is complete I'd like it to close that browser window that called it.
Is there a way to do this other than to return a view with ja开发者_如何学运维vascript in the "onReady" that tells it to close?
No, there isn't a way to achieve this from the server without using javascript (or returning a view that will execute this javascript).
Put this in your view:
@if (ViewBag.ShouldClose) {
<script type="text/javascript">
window.close();
</script>
}
Then if you set the ShouldClose property, it'll run that script and should close the window.
// in your controller
ViewBag.ShouldClose = true;
Note: I did this from the editor so you might have to tweak the view syntax to get it to parse right.
I had the same question and the answer of @Michael Kennedy was exactly what I needed! Since I am using MVC 2 I did have to alter the syntax. I'll put it here as a reference for others.
In the view:
<% if ((bool)ViewData["ShouldClose"]) { %>
<script type="text/javascript">
window.close();
</script>
<% } %>
In the controller:
ViewData["ShouldClose"] = true;
Don't forget to set the ViewData in each call to the view otherwise you'll get a NullReference for the cast to bool.
精彩评论