Use Images, CSS and JavaScript in ASP.NET Core Razor Pages

On the Visual Studio, create new ASP.NET Core Web Application project

Select Empty Template

Click Ok button to Finish




Create new folder named wwwroot

Create new folder named images in wwwroot folder. Copy images need to use in project to images folder.

Create new folder named css in wwwroot folder. In this folder, create new css file named style.css as below:

.format {
    color: red;
    font-size: 20px;
}

img {
    width: 120px;
    height: 100px;
}

Create new folder named js in wwwroot folder. In this folder, create new javascript file named mylib.js as below:

function clickMe() {
    alert('Hello World');
}




Open Startup.cs file and add new configurations as below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreRazorPagesWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            app.UseMvc();
        }
    }
}

Create new folder named Pages. In this folder, create new Razor Page named Index as below:

@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.IndexModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="~/css/style.css" rel="stylesheet" type="text/css" />
    <script src="~/js/mylib.js"></script>
</head>
<body>

    <h3 class="format">Index Page</h3>
    <img src="~/images/thumb1.gif" onclick="clickMe()" />

</body>
</html>
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class IndexModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}




Open Index Razor Page with following url: http://localhost:1115

Output