使用MVC打开一个新窗口

3

我需要一个按钮,点击后能在新窗口打开我的http://fake.com/Report/PageFixes...页面。目前我已经在表单中添加了一个按钮,但如果有更好的方法,我也愿意尝试。

<% using (Html.BeginForm("PageFixes", "Report", new { id = 9 }, FormMethod.Get, new { onSubmit="window.open()" })) %>
<% { %>
    <%= Html.CSButton(new ButtonViewData() { Text = "Submit" })%>
<% } %>
3个回答

6
您不需要添加一个表单。只需在视图中添加以下HTML代码即可:
<button type="button" onclick="window.open('<%= Url.Action("PageFixes", "Report", new { id = "9" } ) %>', '_blank'); return false;">submit</button>

我不确定您是如何获取ID9,但我猜想它来自于您的模型,因此您可以将"9"替换为Model.ID或其他内容。

关键是使用Url.Action生成URL,然后只需使用基本的JavaScript函数window.open在新的浏览器窗口中打开URL即可。


对我来说运行得非常好。谢谢! - jason
谢谢你的建议。这就是对我有用的东西。<a href="" onclick="window.open('@Url.Action("BlackBerrySummarySMACExport", new { departmentId = @ViewBag.DeptId })', '_blank', 'menubar=no'); return false;">企业黑莓摘要SMAC报告</a> - Kremena Lalova

3
如何在按钮上使用JavaScript,可以像这样:
<button type="button" onclick="window.open('http://fake.com/Report/PageFixes/9')">submit</button>

或者如果您更愿意动态构建URL

<button type="button" onclick="window.open('<%= Request.Url.Scheme + "://"+Request.Url.Authority+Request.ApplicationPath %>Report/PageFixes/9')">submit</button>

0

你仍然可以使用onclick JavaScript函数的老式方法来实现。这是我如何做到的,我需要将模型中的ID传递到我的新URL,该URL指向同一项目目录分支中的另一个视图文件夹:

<input type="button" id="@Model.Id" data-id="@Model.Id" onclick="openUrl(this)" data-myurl="/OtherBranch/Detail?id=@Model.Id" />

function openUrl(e) {
    var id = e.id;
    var obj = $("[id='"+id+"']");
    var currentUrl = window.location.href;
    var newBranch = obj.attr('data-myurl');
    var newUrl = currentUrl.split('/FirstBranch')[0] + newBranch;
    window.open(newUrl, "", "height=600,width=400,addressbar=no,menubar=no"); // pop-up window -- should probably ensure no master page is used
    //window.location.href = newUrl; // <-- total redirect option
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接