Razor + External JS

ANB 181 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
ASP.NET
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
    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.

    0 comments No comments