ASP.NET MVC: how to close a browser window instead of returning?

I have an instance where, of my own choice, but I have a secondary popup in the browser. After submitting the form back to the server-side MVC method, after completing this method, I would like to close this browser window that caused it.

Is there a way to do this otherwise than return the view using javascript in "onReady" that tells it to close?

+3
source share
3 answers

No, this cannot be achieved from the server without using javascript (or returning a view that this javascript will execute).

+7
source

Put it in your opinion:

@if (ViewBag.ShouldClose) {
    <script type="text/javascript">
        window.close();
    </script>  
}

, ShouldClose, script .

// in your controller
ViewBag.ShouldClose = true;

. , , .

+5

I had the same question, and Michael Kennedy's answer was exactly what I needed! Since I am using MVC 2, I had to change the syntax. I will put it here as a link to others.

In view:

<% if ((bool)ViewData["ShouldClose"]) { %>
<script type="text/javascript">
   window.close();
</script>
<% } %>

In the controller:

ViewData["ShouldClose"] = true;

Remember to set the ViewData in each call for the view, otherwise you will get a NullReference for the cast for bool.

+2
source

All Articles