combine server side razor boolean with client side

2019-06-11 06:26发布

I have a situation where I need to decide to include a html link based on client side boolean value and server side boolean value like this :

const preloadSupported = () => {
              const link = document.createElement('link');
              const relList = link.relList;
              if (!relList || !relList.supports)
                return false;
              return relList.supports('preload');
            };

if (!@Model.oldLayout && preloadSupported())
{
    <link rel="preload" href="staticResource.js" as="script" />
}

or

if (@Model.oldLayout) //server side boolean
{
    if (preloadSupported()) // client side boolean
    {
        @foreach (var url in Model.cssUrls)
        {
            <link rel="preload" href="@Html.StaticFile(url)" as="script"/>
        }
    }
    else
    {
        @foreach (var url in Model.cssUrls)
        {
            <link rel="prefetch" href="@Html.StaticFile(url)"/>
        }
    }   
}

how should I do that? I tried different variations none of them worked! thanks for your help in advance

2条回答
做个烂人
2楼-- · 2019-06-11 06:58

You need to place this code in your razor file inside your javascript tags for the client.

Pass in the urls for the scripts from the server, or hard code it in the javascript code.

<script>
    @if (!Model.OldLayout)
    {
        <text>
        if (preloadSupported())
        {
            loadScript("/scripts/script01.js");
            loadScript("/scripts/script02.js");

            function loadScript(url)
            {
                var script = document.createElement('script');
                document.head.appendChild(script);
                script.onload = function()
                {
                    // Do anything with the script here (because it's now loaded)
                };
                script.src = url;
            }
        }
        </text>
    }
</script>
查看更多
Anthone
3楼-- · 2019-06-11 07:16

Mixing server side and client side code can be tricky. You can use rendered server side code with javascript, but it can't really work the other way around.

In your first example, the if-statement would have to be:

if (!('@Model.oldLayout' === 'True') && preloadSupported())
{
    //..link
}

The problem here is that the link wouldn't exist until the page was parsed and rendered. You could perhaps use document.write, createElement or jquery $.load() to add it, but that depends on what the external file is used for and when it has to be added.

Best bet would really be to check for "preloadSupport" earlier, or redirect the visitor if preload is supported and create a new response.

查看更多
登录 后发表回答