In ASP.NET 5, There is no such Scripts.Render
method. To render scripts, you may use the environment tag helper.
It is not necessary that you should use the environment tag helper. You can directly put your script tags in the layout file. But the environment helpers allows us to conditionally render scripts based on the environment. (Minified-Bundled version vs All Un minified version)
Here is the syntax, you can include this in your Layout file.
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/js/d3.js"></script>
</environment>
<environment names="Staging,Production">
<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery">
</script>
<script src="~/js/d3.min.js" asp-file-version="true"></script>
</environment>
Assuming you have the script files d3.js
and d3.min.js
exist in ~/js
directory.
Also you need to make sure that you have invoked the UseStaticFiles()
method inside the Configure()
method(inside Startup.cs)
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
//Other configuration goes here
app.UseStaticFiles(); // This enables static file serving from the app.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
UseStaticFiles()
extension method enables static file serving including js files,css files etc..
When you run the application in Development mode, It will render the script tags inside environment "Development"
and when you run it in either Staging or Production, It will render script tags under the "Staging,Production"
environment.
You can change the environment value by right clicking on the project and select properties->Debug
and specify the value of the environment variable Hosting:Environment
You can see that i have included the minified version of js files in the Staging/Production enviornment. This is not necessary but preferred approach as it will save some bandwidth. (You can put the un-minified version also there instead of minified if you really want to do that.). If you have a single bundled file, you may use that also here instead of individual files.
If you already do not have a minified version, you can generate that by running the gulp task for minification.(This is included in the default gulp.js
file which is in the new web app template). You just need to open up the task runner and run the minification task.
If you do not wish to manually run this every time, You may select Bindings -> Before build
so that this will automatically run that purticular gulp task everytime you build your project.