How to execute a JavaScript function from MVC Razor code for an included JS file?

13,294

Make sure you put your <script /> tag to import the JS file before your call to the loginError(); function. You might want to put it in your HTML's <head>.

Share:
13,294
ElHaix
Author by

ElHaix

Solutions architect in a drive for consistently learning and assisting when possible.

Updated on June 09, 2022

Comments

  • ElHaix
    ElHaix almost 2 years

    In a JavaScript block in a MVC4 Razor view, I can do:

    function loginError() {
        $('#loginFailed').fadeIn();
    }
    
    @if (!ViewData.ModelState.IsValid)
    {
        // login failed
        @:loginError();
    }
    

    However, if loginError() is contained in an external JS file, I get the following error:

    Uncaught ReferenceError: loginError is not defined

    How can I execute JS functions from .Net code in a Razor view for imported JS files?