簡體   English   中英

在 MVC .cshtml 頁面中使用 Javascript if else

[英]Using Javascript if else inside MVC .cshtml page

有沒有辦法在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,則使用<embed>標簽,否則使用<object>標簽。

任何建議或幫助將不勝感激。

提前致謝

由於DetectIE()是一個 JS 函數,因此您不能將其用作 Razor @if塊的比較。 您應該使用jQuery.append()將它放在<script> ,以將正確的標簽附加到目標元素中:

<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
}

您不能直接在 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM