In this article I will explain with an example, how to use Static files (Images, CSS and JS files) in ASP.Net Core MVC (.Net Core 7).
Static files such as Image files, CSS files and
JavaScript JS files does not work in ASP.Net Core unless it is placed at proper location with the necessary settings.
Static Files Location
The Static Files are stored inside the wwwroot Folder (Directory).
Stylecss.css
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;
}
JavaScript.js
The JS file consists of following
JavaScript function inside which the name of the Image is set in the
img element and image is displayed.
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
Inside the Startup.cs class, the UseStaticFiles method of IApplicationBuilder interface is called which makes Static files accessible in ASP.Net Core.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseStaticFiles();
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
View
HTML Markup
Inside the View first the CSS and JS files are inherited inside the HEAD tag.
The View consists of an HTML Table which consists of following elements:
TextBox – For capturing Image file name.
Button – For calling ShowName JavaScript function.
The
Button has been assigned with an
onclick JavaScript function.
When the Button is clicked, the
ShowName JavaScript function (discussed later) is called.
Img – For displaying Image.
@{
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>
Screenshot
Downloads