Razor in javascript file

Asked

Viewed 724 times

1

I have a little code that works on _Layout:

$.ajax({
    type: "POST",
    url: "@Url.Action("Action", "Controller")",
    success: function () {
          //Seu código aqui ...
    }
});

So far, so good, only _Layout is getting really big. so I want to add a file javascript and add her into _Layout.

Only the problem is javascript file. It does not recognize '@'.

How can I fix this?

2 answers

3


It doesn’t solve. Javascript is one thing, Razor is another.

The @ is part of the Razor syntax and means that this will be processed on the server side before the response is sent to the client. Javascript files are sent to the client in the same way as they are written, so they are not pre-processed by a mechanism like Razor.

There are some alternatives:

  1. Create a view with the section of scripts and upload it to the _Layout file, using RenderPage.

    Something like:

    @RenderPage("~/Views/Shared/_Scripts.cshtml")
    
  2. Using a library like Razorjs to pre-process Javascript files.

  • The library Razorjs is reliable ? Because it’s been 6 years without update.

  • 1

    There is no way to know, I never used. But it is very likely that it meets the most basic cases, as this of your publication.

2

Create a. js file and enter your code:

$.ajax({
    type: "POST",
    url: "Action",
    success: function () {
          //Seu código aqui ...
    }
});

And then in your View Layout, you instance:

@section scripts{
   <script src="caminho do seu arquivo js"></script>
}

I don’t believe we can use Razor Helpers in . js files.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.