Razor + External JS

ANB 176 Reputation points
2021-11-18T19:02:22.213+00:00

On my current MVC project, I have my View (cshtml) containing HTML + a long JS at the bottom of the page.

eg:
<div class="row">
<div class="col-12">
<input type="text" id="myInput" />
<p>Part of my Razor View</p>
</div>
</div>
</div>

<script type="text/javascript">
...
</script>

But I want to remove the entire <script> from there and move to an external file.

The problem is on this JS, I have things like:
var productId = @默 .ProductId;

So moving to an external file, the code breaks.
What would be the solution for it ?

Thanks,

ASP.NET MVC
ASP.NET MVC
A Microsoft web application framework that implements the model-view-controller (MVC) design pattern.
592 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Lan Huang-MSFT 9,041 Reputation points Microsoft Employee
    2021-11-19T08:04:32.747+00:00

    Hi @ANB ,
    You need to create a variable in the view in the script tag, and then use the variable in the external js file.

    <script>  
    var productId = @Model.ProductId;  
    </script>  
    

    Then you can use ProductId in the js file.
    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    No comments