如果在MVC .cshtml页面内使用Javascript

奥威斯·艾哈迈德(Owais Ahmed)

MVC CSHTML页面中是否有其他方法可以使用

 <div class="primary-content">
            if(DetectIE())
            {
            <embed data-bind="attr: { src: data.files()[currentPage()] + '#toolbar=0&amp;navpanes=0&amp;scrollbar=0' }" type="application/pdf" style="width: 100%; height: 800px !important;">
            }
            else
            {
            <object data-bind="attr: { data: data.files()[currentPage()] + '#toolbar=0&amp;navpanes=0&amp;scrollbar=0' }" type="application/pdf" width="100%" height="600px"></object>
            }
        </div>

我有一个JavaScript代码可以检测当前浏览器是否为Internet Explorer。如果是IE,则<embed>使用<object>标签,否则使用标签。

任何建议或帮助,将不胜感激。

提前致谢

山本哲也

由于DetectIE()是JS函数,因此不能将其用作与Razor@if块的比较您应该将其放入<script>其中,jQuery.append()以将适当的标签附加到目标元素中:

<script>
$(function() {
    // other stuff

    if (DetectIE())
    {
        $('#targetElement').append("<embed data-bind=\"attr: { src: data.files()[currentPage()] + '#toolbar=0&amp;navpanes=0&amp;scrollbar=0' }\" type=\"application/pdf\" style=\"width: 100%; height: 800px !important;\">");
    }
    else
    {
        $('#targetElement').append("<object data-bind=\"attr: { data: data.files()[currentPage()] + '#toolbar=0&amp;navpanes=0&amp;scrollbar=0' }\" type=\"application/pdf\" width=\"100%\" height=\"600px\"></object>");
    }
});
</script>

目标元素的示例:

<div id="targetElement" class="primary-content"></div>

如果要从控制器端检查IE的任何版本,可以使用以下命令:

bool isIE = (Request.Browser.Browser == "IE" || Request.Browser.Browser == "InternetExplorer");

然后将值传递给ViewBag

ViewBag.IsIE = isIE;

JS用法示例

if (@ViewBag.IsIE)
{
   // render embed tag
}
else
{
   // render object tag
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章