Razor + External JS

ANB 181 Reputation points

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

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

<script type="text/javascript">

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 ?


A set of technologies in the .NET Framework for building web applications and XML web services.
3,168 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Lan Huang-MSFT 22,906 Reputation points Microsoft Vendor

    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.

    var productId = @Model.ProductId;  

    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.

    0 comments No comments