[asp.net-mvc-4] Open mvc view in new window from controller

Is there any way to open a view from a controller action in a new window?

public ActionResult NewWindow()
{
    // some code
    return View();
}

How would I get the NewWindow.cshtml view to open in a new browser tab?

I know how to do it from a link in the view - that is not the question. Has anyone figured out a way to do it from the controller action?

This question is related to asp.net-mvc-4

The answer is


@Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank",@class="edit"})

   script below will open the action view url in a new window

<script type="text/javascript">
    $(function (){
        $('a.edit').click(function () {
            var url = $(this).attr('href');
            window.open(url, "popupWindow", "width=600,height=800,scrollbars=yes");
            });
            return false;
        });   
</script>

You're asking the wrong question. The codebehind (controller) has nothing to do with what the frontend does. In fact, that's the strength of MVC -- you separate the code/concept from the view.

If you want an action to open in a new window, then links to that action need to tell the browser to open a new window when clicked.

A pseudo example: <a href="NewWindow" target="_new">Click Me</a>

And that's all there is to it. Set the target of links to that action.


I assigned the javascript in my Controller:

model.linkCode = "window.open('https://www.yahoo.com', '_blank')";

And in my view:

@section Scripts{
    <script @Html.CspScriptNonce()>

    $(function () {

        @if (!String.IsNullOrEmpty(Model.linkCode))
        {
            WriteLiteral(Model.linkCode);
        }
    });

That opened a new tab with the link, and went to it.

Interestingly, run locally it engaged a popup blocker, but seemed to work fine on the servers.


Yeah you can do some tricky works to simulate what you want:

1) Call your controller from a view by ajax. 2) Return your View

3) Use something like the following in the success (or maybe error! error works for me!) section of your $.ajax request:

$("#imgPrint").click(function () {
        $.ajax({
            url: ...,
            type: 'POST', dataType: 'json',
            data: $("#frm").serialize(),
            success: function (data, textStatus, jqXHR) {
                //Here it is:
                //Gets the model state
                var isValid = '@Html.Raw(Json.Encode(ViewData.ModelState.IsValid))'; 
                // checks that model is valid                    
                if (isValid == 'true') {
                    //open new tab or window - according to configs of browser
                    var w = window.open();
                    //put what controller gave in the new tab or win 
                    $(w.document.body).html(jqXHR.responseText);
                }
                $("#imgSpinner1").hide();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // And here it is for error section. 
                //Pay attention to different order of 
                //parameters of success and error sections!
                var isValid = '@Html.Raw(Json.Encode(ViewData.ModelState.IsValid))';                    
                if (isValid == 'true') {
                    var w = window.open();
                    $(w.document.body).html(jqXHR.responseText);
                }
                $("#imgSpinner1").hide();
            },
            beforeSend: function () { $("#imgSpinner1").show(); },
            complete: function () { $("#imgSpinner1").hide(); }
        });            
    });      

You can use as follows

public ActionResult NewWindow()
{
    return Content("<script>window.open('{url}','_blank')</script>");
}

You can use Tommy's method in forms as well:

@using (Html.BeginForm("Action", "Controller", FormMethod.Get, new { target = "_blank" }))
{
//code
}

I've seen where you can do something like this, assuming "NewWindow.cshtml" is in your "Home" folder:

string url = "/Home/NewWindow";
return JavaScript(string.Format("window.open('{0}', '_blank', 'left=100,top=100,width=500,height=500,toolbar=no,resizable=no,scrollable=yes');", url));

or

return Content("/Home/NewWindow");

If you just want to open views in tabs, you could use JavaScript click events to render your partial views. This would be your controller method for NewWindow.cshtml:

public ActionResult DisplayNewWindow(NewWindowModel nwm) {
    // build model list based on its properties & values
    nwm.Name = "John Doe";
    nwm.Address = "123 Main Street";
    return PartialView("NewWindow", nwm);
}

Your markup on your page this is calling it would go like this:

<input type="button" id="btnNewWin" value="Open Window" />
<div id="newWinResults" />

And the JavaScript (requires jQuery):

var url = '@Url.Action("NewWindow", "Home")';
$('btnNewWin').on('click', function() {
    var model = "{ 'Name': 'Jane Doe', 'Address': '555 Main Street' }"; // you must build your JSON you intend to pass into the "NewWindowModel" manually
    $('#newWinResults').load(url, model); // may need to do JSON.stringify(model)
});

Note that this JSON would overwrite what is in that C# function above. I had it there for demonstration purposes on how you could hard-code values, only.

(Adapted from Rendering partial view on button click in ASP.NET MVC)