Open mvc view in new window from controller
asp.net Mvc-4asp.net Mvc-4 Problem Overview
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?
asp.net Mvc-4 Solutions
Solution 1 - asp.net Mvc-4
This cannot be done from within the controller itself, but rather from your View. As I see it, you have two options:
-
Decorate your link with the "_blank" attribute (examples using HTML helper and straight HMTL syntax)
@Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank"})
<a href="@Url.Action("Action", "Controller")" target="_blank">Link Text</a>
-
Use Javascript to open a new window
`window.open("Link URL")`
Solution 2 - asp.net Mvc-4
You can use Tommy's method in forms as well:
@using (Html.BeginForm("Action", "Controller", FormMethod.Get, new { target = "_blank" }))
{
//code
}
Solution 3 - asp.net Mvc-4
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.
Solution 4 - asp.net Mvc-4
Yeah you can do some tricky works to simulate what you want:
-
Call your controller from a view by ajax.
-
Return your View
-
Use something like the following in the
success
(or maybeerror
! 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(); } });
});
Solution 5 - asp.net Mvc-4
You can use as follows
public ActionResult NewWindow()
{
return Content("<script>window.open('{url}','_blank')</script>");
}
Solution 6 - asp.net Mvc-4
@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>
Solution 7 - asp.net Mvc-4
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 https://stackoverflow.com/questions/29142422/rendering-partial-view-on-button-click-in-asp-net-mvc)
Solution 8 - asp.net Mvc-4
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.