Owais Ahmed
Owais Ahmed

Reputation: 1438

Using Javascript if else inside MVC .cshtml page

Is there a way to use if else statment inside MVC cshtml page

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

I have a javascript code to detect if the current browser is Internet explorer or not . If it is a IE then <embed> tag is used otherwise <object> tag is used.

Any suggestions or help would be appreciated.

Thanks in advance

Upvotes: 1

Views: 2703

Answers (2)

Sreenath Ganga
Sreenath Ganga

Reputation: 736

You cannot use javascript function inside razor directly..so bettter use Request .Browser to Get the Browsername

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

}
@if (IsIE)
{
    // Your Razor here
}
else
{
    //  Your Razor here
}

Upvotes: 0

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

Since DetectIE() is a JS function, you can't use it as comparison to Razor @if block. You should put it inside <script> with jQuery.append() to append the proper tag into target element:

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

Example of the target element:

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

If you want to check any version of IE from controller side, you can use this:

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

And then pass the value to ViewBag:

ViewBag.IsIE = isIE;

JS usage example

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

Upvotes: 1

Related Questions