Static Files (Images, CSS and JS files) in ASP.Net Core

I’ll demonstrate how to use static files (images, CSS, and JS files) with ASP.Net Core in this article using an example.
Static assets, including image files, CSS files, and JavaScript JS files, do not function with ASP.Net Core unless they are placed in the correct area with the project and certain settings are also configured.

Folder Location to keep Static Files (Images, CSS and JS files) in ASP.Net Core

Three folders—CSS, Images, and Scripts—have been created inside the wwwroot folder, as shown in the screenshot below. The default folder supplied by ASP.Net Core for storing all static files, including image files, CSS files, and JavaScript JS files, is called wwwroot.

 

Contents of the CSS and JavaScript JS files

body
{
    font-family: Arial;
    font-size: 10pt;
}
 
table
{
    border: 1px solid #ccc;
    border-collapse: collapse;
}
 
table th
{
    background-color: #F7F7F7;
    color: #333;
    font-weight: bold;
}
 
table th, table td
{
    padding: 5px;
    border: 1px solid #ccc;
}
 
#img
{
    height: 80px;
    width: 80px;
}
function ShowName() {
    var name = document.getElementById("txtName").value;
    var img = document.getElementById("img");
    img.src = "/images/" + name + ".png";
    img.alt = name;
    document.getElementById("trImage").style.display = "table-row";
};

Allowing access to Static Files in ASP.Net Core

You must use the function UseStaticFiles inside the Startup.cs class to allow static files. The Static files won’t be available unless this function is called.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseStaticFiles();
}

Controllar:

The View is the only thing returned inside of this Controller.

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

View:

The CSS and JavaScript JS files are inherited by the View and used there.
The ShowName JavaScript method is invoked when the Submit button is pressed, and it uses the value entered in the Name TextBox to display the Image from the Images folder.

@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    <link href="~/CSS/Stylecss.css" rel="stylesheet"/>
    <script src="~/Scripts/JavaScript.js"></script>
</head>
<body>
    <table>
        <tr>
            <td>Name</td>
            <td><input type="text" id="txtName"/></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="button" id="btnSubmit" value="Submit" onclick="ShowName();"/></td>
        </tr>
        <tr id="trImage" style="display:none">
            <td colspan="2" align="center"><img id="img" alt=""/></td>
        </tr>
    </table>
</body>
</html>

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories