admin管理员组

文章数量:1327661

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?

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?

Share Improve this question asked Jan 16, 2014 at 21:33 ElHaixElHaix 13k27 gold badges124 silver badges210 bronze badges 2
  • 1 as long as the javascript file is referenced before you attempt the call everything should work fine – Matt Bodily Commented Jan 16, 2014 at 21:35
  • Any update? I am facing the same issue. here is my code <script type="text/javascript"> function GetconfigColCount() { return 3; } </script> </head> @{ ViewBag.colCount = @:GetconfigColCount(); } It gives ; missing error, if i removed the @{ ... } then error goes. I put the @{..} inside the head , and inside the script but issue still there. I like to call it before body tag part as the count will effect the dynamic table formation in the body before ready function call. – AKS Commented Feb 25, 2015 at 7:42
Add a ment  | 

1 Answer 1

Reset to default 4

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

本文标签: jqueryHow to execute a JavaScript function from MVC Razor code for an included JS fileStack Overflow