will the cshtml auto contain the cshtml.js and cshtml.css?

mc 3,641 Reputation points
2022-09-01T00:23:58.577+00:00

I am using .net core web application.

There is a Index.cshtml and Index.cshtml.js and Index.cshtml.css will the Index.cshtml auto contain Index.cshtml.js?

Need I add

<script type="text/javascript" src="/Index.cshtml.js" ></script>

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,157 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,252 questions
{count} votes

Accepted answer
  1. Ruikai Feng - MSFT 2,526 Reputation points Microsoft Vendor
    2022-09-01T02:40:13.677+00:00

    Hi,@mc
    there's the concept of CSS isolation,you could check this document,but it will only work for css files

    In MVC projects, if your views share the same layout,you could try to get the name of current controller and action from viewcontext and bind the js source as below:
    in layout:

    @{      
        var action = ViewContext.RouteData.Values["action"].ToString();  
        var controller = ViewContext.RouteData.Values["controller"].ToString();  
        var source = string.Format("https://localhost:5001/js/{0}.js", action);  
    }  
    
    <script src=@source></script>  
    

    Index.js:

    window.onload = function () {  
        alert("Index")  
    }  
    

    Privacy.js:

    window.onload = function () {  
        alert("Privacy")  
    }  
    

    Result:
    236650-qa-91.gif

    In RazorPage,you could try ViewContext.RouteData.Values["page"].ToString()

    ----------

    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.
    Best regards
    RuikaiFeng

    0 comments No comments

0 additional answers

Sort by: Most helpful