Javascript with some Razor is not working externally

I have a javascript function

 function GotoFPLoginPage() {
            var url = '@(ViewBag.Title)';
            if (url.includes("Home")) {
                window.location.href = "/FPLogin/Index";
            }
        }

Implementation:

<html onclick="GotoFPLoginPage()">

The purpose of this is when the user click any part of the page it will redirect to another target page.

This example is working fine if i use the function itself inside my _layout page but when i tried to make it a javascript file and make a unique name Custom_JSFile then calling the GotoFPLoginPage() it is not working.

 @Scripts.Render("~/Scripts/Custom_JSFile.js")

Any idea is highly appreciated.

1 answer

  • answered 2019-04-15 16:17 Jacob

    Do you modify the JavaScript function at all when you move it into a separate JavaScript file?

    This line will not work in a .js file as you do not have access to the ViewBag.

    var URL = '@(ViewBag.Title)';
    

    The reason this works in a .cshtml file is because you are using razor syntax to access a c# object. This will insert the value from the object into the JavaScript and the result is what will be evaluated.

    Since razor syntax is not valid in a JavaScript file (you also have zero context of the ViewBag in a JavaScript file), this will not work and your URL value will literally equal "@(ViewBag.Title)".

    You will have to put the value from ViewBag.Title somewhere that JavaScript is able to access it.