Razor in javascript file

1

I have a small code that works in _Layout :

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

So far everything works fine, but _Layout is getting too big. so I want to add a javascript file and add it to _Layout .

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

How can I resolve this?

    
asked by anonymous 28.07.2017 / 21:51

2 answers

3

It does not resolve. JavaScript is one thing, Razor is another.

@ 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 preprocessed by a mechanism like Razor.

There are a couple of alternatives:

  • Create a view with the scripts section and load it into the _Layout file, using RenderPage .

    Something like:

       
    @RenderPage("~/Views/Shared/_Scripts.cshtml")
    
  • Use a library such as RazorJS to preprocess JavaScript files.

  • 28.07.2017 / 21:57
    2

    Create an .js file and place your code:

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

    And there in your View Layout, you instantiate:

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

    I do not think you can use Razor Helpers in .js files.

        
    28.07.2017 / 21:58