@foreach (var item in Model.policydata)
{
<tr align="center">
<td>
@Html.DisplayFor(modelitem => item.Name)
</td>
<td>
@Html.DisplayFor(modelitem => item.PolicyID)
</td>
<td>
@Html.DisplayFor(modelitem => item.CustomerID)
</td>
<td>
<a onclick="OpenRepositoryFile()" href="@string.Format("http://repository.website.com/{0}/{1}.pdf", Model.PolicyName, item.CustomerID)">View</a>
</td>
</tr>
}
</table>
<script>
function OpenRepositoryFile()
{
var win = window.open('', '_blank');
if(win)
{
//Browser has allowed it to be opened
win.focus();
}else{
//Broswer has blocked it
alert('This application feature requires Popups Enabled. Please right click to open in a new Tab or change your Browser settings');
}
}
</script>
我已经得到了这个 Razor 代码和这个 Javascript 函数。基本上,Razor 链接是根据从模型变量检索的数据构建的,Javascript 函数会打开一个新窗口/选项卡(取决于设置),或者如果浏览器设置不允许弹出窗口,则会提醒用户。单独使用时,两者都可以正常工作。
问题就在这里。我希望 Razor 构建的链接作为 Javascript 函数的 window.open 命令中的参数。
我本以为在 Javascript 或 JQuery 中,会有一个 string.format() 函数,就像现在在 .Net 中一样,但是,没有..
有没有办法通过 ID 获取 Razor 在 Anchor 标记内构建的 Href 字符串属性?或者对此有任何其他建议吗?
谢谢
最佳答案
您可以使用 jQuery 轻松完成此操作,只需通过 jQuery 将事件与此 anchor 标记绑定(bind),如下所示:
HTML
<a id="ancWindow"
href="@string.Format("http://repository.website.com/{0}/{1}.pdf", Model.PolicyName, item.CustomerID)">View</a>
jQuery
$(document).ready(function() {
$('#ancWindow').click(function(e) {
e.preventDefault(); // <- used to prevent redirection from anchor
var win = window.open(this.href, '_blank');
if(win) {
//Browser has allowed it to be opened
win.focus();
} else{
//Broswer has blocked it
alert('This application feature requires Popups Enabled. Please right click to open in a new Tab or change your Browser settings');
}
});
});
注意:确保您有 jQuery 文件的引用。
关于javascript - 在 Javascript 函数中包含 Razor 格式的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30422070/