【问题标题】:Using Javascript if else inside MVC .cshtml page在 MVC .cshtml 页面中使用 Javascript if else
【发布时间】:2018-11-01 04:15:47
【问题描述】:

有没有办法在 MVC cshtml 页面中使用 if else 语句

 <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 则使用&lt;embed&gt; 标签,否则使用&lt;object&gt; 标签。

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

提前致谢

【问题讨论】:

  • 只需使用@if (DetectIE()) { // embed tag } else { // object tag } 语句。但是DetectIE() 是做什么的呢?
  • DetectIEit 是一种检测 Internet Explorer 的 JavaScript 方法
  • @if 将使用 c# if else 不是 javascript if else
  • 不,你不能在 Razor if 语句中使用 JS 方法。将 if 语句放在 &lt;script&gt; 标记内,并在元素后附加 $.append('&lt;embed&gt;...&lt;/embed&gt;') 之类的内容。
  • 使用Request.Browser 来确定控制器中的浏览器可能更容易,然后只需将bool 属性传递给您的视图,指示其是否为IE(作为视图模型属性或ViewBag 属性)

标签: javascript c# asp.net-mvc razor


【解决方案1】:

由于DetectIE() 是一个JS 函数,你不能用它来比较Razor @if 块。你应该把它放在&lt;script&gt;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
}

【讨论】:

    【解决方案2】:

    你不能直接在 razor 中使用 javascript 函数。所以最好使用 Request .Browser 来获取浏览器名称

    @{bool IsIE = false ;
    if (Request.Browser.Type.ToUpper().Contains("IE"))
    { 
        IsIE = true;
    }
    
    }
    @if (IsIE)
    {
        // Your Razor here
    }
    else
    {
        //  Your Razor here
    }
    

    【讨论】:

    • 我的方法是javascript方法
    猜你喜欢
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    相关资源
    最近更新 更多