How to add css file to cshtml file? - html

I've been trying to add a css file to style a cshtml file, and so far I've been unsuccessful.
Here's what I've tried to do:
#model mvc.Models.LoginViewModel
#{
ViewData["Title"] = "Login";
}
<head>
<div class="text-center">
<h1 class="display-4">Login Page</h1>
</div>
<link rel="stylesheet" href="~/Content/login.css" type="text/css" />
</head>
Here is the directory tree with the two files I'm trying to link
Edit: when I put the css styling in a "style" tag in the cshtml then it works. I was hoping there was a way to do it with a css file.
Can you please help me?
Thank you.

From your project structure, I think you may misunderstand asp.net and asp.net core. .NET 5 is the next version of .NET Core.
You use .NET 5.0, so if you want to directly add css reference, you need add these static files to wwwroot folder in root project. Be sure you have added static files middleware in Startup.cs:
app.UseStaticFiles(); //be sure add this...
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
Then add reference like below:
<link rel="stylesheet" type="text/css" href="~/login.css" />
Reference: Serve files in web root
If you put static files to other folder(e.g Content folder) which is in root project, you need add the following code to Startup.cs first:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseHttpsRedirection();
app.UseStaticFiles(); // For the wwwroot folder.
// using Microsoft.Extensions.FileProviders;
// using System.IO;
app.UseFileServer(new FileServerOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(env.ContentRootPath, "Content")),
RequestPath = "/StaticFiles",
EnableDirectoryBrowsing = true
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Add static files reference like below:
<link rel="stylesheet" type="text/css" href="/StaticFiles/login.css" />
Reference: Serve files outside of web root

Related

How to link css file with ejs?

In my directory I have created a public folder in which I have put another folder named css in which is located styles.css. In another folder in my directory named views I have put my ejs file, with which I want to link styles.css like this:
<link rel="stylesheet" type="css/text" href="css/styles.css">
However this does not work.
I dont even get an error in my browsers console.
If you are using npm and Express, we need to set up a public folder for the static content (like your css file):
1) In your root folder, create a folder called 'public', then another one inside called 'css' and place your styles.ccs file in there.
2) In your JS application file (e.g. app.js), we need to have something like this:
//jshint esversion:6
const express = require('express');
const ejs = require("ejs");
const app = express();
app.set('view engine', 'ejs');
app.use(express.static("public"));
app.get('/', (req, res) => {
res.render('index', { foo: 'FOO' });
});
3) In your root folder, create a folder called 'views' and inside place the EJS file you want to render (e.g. index.ejs), stablishing the link like this: <link rel="stylesheet" href="/css/styles.css">:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/css/styles.css">
<title>Document</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
In this case, you should be able to see the css code applied in the home route "/", rendering the index.ejs file. I hope it help you!

ASP.NET Core - serve different HTML file for SPA?

Question
How can I serve different HTML (entry) files for an SPA application (Vue) in ASP.NET Core?
Explanation
Depending on a condition, I would like to serve a different HTML page (much like a controller would do for a non-SPA). The page would still include the entry point for Vue apps <div id="app">, but some other changes should be done before serving the HTML.
I know I somehow have to change the startup.cs file because that renders the HTML with app.UseStaticFiles() and app.UseSPAStaticFiles()
Example
Condition 1 is fulfilled, base.html is served from client -> public -> base.html
Condition 2 is fulfilled instead, special.html is served from client -> public -> special.html
Code
The basic HTML looks something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>Title</title>
</head>
<body>
<noscript>
<strong>We're sorry but this webpage doesn't work properly without JavaScript enabled. Please enable it to
continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
The important parts of startup.cs looks like this:
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
// ....
app.UseStaticFiles();
app.UseSpaStaticFiles();
// ....
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
if (env.IsDevelopment())
{
endpoints.MapToVueCliProxy(
"{*path}",
new SpaOptions { SourcePath = "ClientApp" },
npmScript: "serve",
regex: "Compiled successfully");
}
// Add MapRazorPages if the app uses Razor Pages. Since Endpoint Routing includes support for many frameworks, adding Razor Pages is now opt -in.
endpoints.MapRazorPages();
});
// ....
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
});

How to load CSS and Bootstrap files into server using node.js?

I have a html file called myfile.html that displays 'Hello World'. My css file called myfile.css is used to insert background image. My bootstrap files are used to insert a image in the form of a circle.
The HTML file is as follows:
<!DOCTYPE html>
<html>
<head>
<title>MY FILE</title>
<link rel="stylesheet" type="text/css" href="public\css\bootstrap.css">
<link rel="stylesheet" type="text/css" href="public\myfile.css">
</head>
<body>
<h1>Hello World!!</h1>
<img src="public\pinky.jpg" class="img-circle">
</body>
</html>
My CSS file is as follows:
body {
background-image: url('fishy.jpg');
}
My node.js file called new.js is as follows:
const express = require('express')
const app = express()
app.use(express.static('public'))
app.get('/',function (req,res) {
console.log(__dirname)
res.sendFile(__dirname+"/myfile.html")
})
app.listen(3000, function() {
console.log('Example app listening on port 3000!')
})
My main folder is called Bootsstrap and it has the following contents:
Bootsstrap
-myfile.html
-public /*Folder*/
/*inside public folder*/
-myfile.css
-css
-js
-fonts
-fishy.jpg /*background image*/
-pinky.jpg /*circular image*/
I open Command Prompt from Bootsstrap folder and run
node new.js
I get the message as:
'Example app listening on port 3000!'
When I open Chrome Browser and type localhost:3000, I get only 'Hello World'.The images are not getting displayed. I get an Error 404.
What can I do in order to run my HTML file in server using node.js by including all my css and bootstrap files?
You must not use the public path in your html. Also, in URLs use always forward slashes. Backslashes are just for Windows directories.
<!DOCTYPE html> <html> <head> <title>MY FILE</title>
<link rel="stylesheet" type="text/css" href="/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="myfile.css">
</head> <body> <h1>Hello World!!</h1>
<img src="pinky.jpg" class="img-circle"> </body> </html>
replace
<link rel="stylesheet" type="text/css" href="public\css\bootstrap.css">
<link rel="stylesheet" type="text/css" href="public\myfile.css">
by
<link rel="stylesheet" type="text/css" href="css\bootstrap.css">
<link rel="stylesheet" type="text/css" href="myfile.css">
If you want to serve static files, such as html files, css, images, you need to make them available for the public. In your existing setup, only myfile.html is available for the public. Since you use css and other files from your server, you need to make them available also. The best way to achieve is to create a public folder and let express to make all the files available in the public folder.
Add to node.js
app.use('/', express.static('public'));
and rename your myfile.html to index.html
and in your index.html file
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="myfile.css">
For example, your node.js should look like something
const express = require('express');
const app = express();
app.use('/', express.static('public'));
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
For more info Serving static files in Express
Edit
Your folder structure should be. no need of bootstap folder
public //public folder
-index.html
-myfile.css
-css
-js
-fonts
-fishy.jpg
-pinky.jpg

Bundle works wrong for css

I have these css files included in layout
<!-- Dropdown Menu -->
<link rel="stylesheet" href="~/Content/superfish.css">
<!-- Date Picker -->
<link rel="stylesheet" href="~/Content/bootstrap-datepicker.min.css">
<!-- CS Select -->
<link rel="stylesheet" href="~/Content/cs-select.css">
<link rel="stylesheet" href="~/Content/cs-skin-border.css">
<!-- Themify Icons -->
<link rel="stylesheet" href="~/Content/themify-icons.css">
<!-- Flat Icon -->
<link rel="stylesheet" href="~/Content/flaticon.css">
<!-- Icomoon -->
<link rel="stylesheet" href="~/Content/icomoon.css">
<!-- Flexslider -->
<link rel="stylesheet" href="~/Content/flexslider.css">
<!-- Style -->
<link rel="stylesheet" href="~/Content/style.css">
now I want to move these files in bundle so I did that:
public static void RegisterBundler(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/Content/style.css").Include(
"~/Content/superfish.css",
"~/Content/bootstrap-datepicker.min.css",
"~/Content/cs-select.css",
"~/Content/cs-skin-border.css",
"~/Content/themify-icons.css",
"~/Content/flaticon.css",
"~/Content/icomoon.css",
"~/Content/flexslider.css",
"~/Content/style.css"
));
BundleTable.EnableOptimizations = true;
}
and in my layout:
#Styles.Render("~/Content/style.css")
but from this:
it goes to this:
some of css code is missing when i open this new css file (from browser developer tool). Especially whole first file is missing (superfish.css) but it is in the same folder as others
What did I wrong?
It might get confused and renders the actual style.css instead of the bundle. Try changing the name of the bundle to something else, i.e. new StyleBundle("~/Content/main.css"). Also, you probably using the render wrong - it should be #Styles.Render("~/Content/style") (note the removed .css part)
Bundling is a new feature in ASP.NET 4.5 that makes it easy to combine or bundle multiple files into a single file.
The Bundle class Include method takes an array of strings, where each string is a virtual path to resource.
Change your code like below:
Note : remove the file extension inside the StyleBundle()
public static void RegisterBundler(BundleCollection bundles)
{
//
bundles.Add(new StyleBundle("~/Content/style").Include(
"~/Content/superfish.css",
"~/Content/bootstrap-datepicker.min.css",
"~/Content/cs-select.css",
"~/Content/cs-skin-border.css",
"~/Content/themify-icons.css",
"~/Content/flaticon.css",
"~/Content/icomoon.css",
"~/Content/flexslider.css",
"~/Content/style.css"
));
BundleTable.EnableOptimizations = true;
}
In Layout: Call like below
#Styles.Render("~/Content/style")
Hope it was helpful

How to copy referenced images in css files to dist folder

I'm having the following index.html file header:
<head>
<title>Visualization</title>
<!-- build:css styles/build.css -->
<link rel="stylesheet" href="../bower_components/bootstrap/css/bootstrap.custom.min.css">
<!-- inject:css -->
<link rel="stylesheet" href="app/index.css">
<link rel="stylesheet" href="app/components/graph/graph.component.css">
<link rel="stylesheet" href="app/components/highchart/highchart.component.css">
<link rel="stylesheet" href="app/components/my-app/app.component.css">
<!-- endinject -->
<!-- endbuild -->
The issue I'm facing right now is the following:
The file ../bower_components/bootstrap/css/bootstrap.custom.min.css contains references to fonts and images.
bower_components
bootstrap
css
bootstrap.custom.min.css
i
logo.png
fonts
glyphicons-halflings-regular.eot
glyphicons-halflings-regular.svg
src
index.html
I would like to write a bower script, that copies this files to the dist folder that I'm using to deploy my application including the actual hierarchy.
As I am having this issue a couple of times I would like to write a general (preferable gulp) task, that takes care of this.
Many thanks for your help.
You have to use a taskrunner to copy your files.
Here is a simple gulp setup to copy images, fonts and css from bower_components to your dist folder.
You may have to adjust the source and dist path.
var gulp = require('gulp');
gulp.task('copy:css', function() {
return gulp.src('./bower_components/path/to/css')
.pipe(gulp.dest('./dist/assets/css'))
});
gulp.task('copy:fonts', function() {
return gulp.src('./bower_components/path/to/fonts')
.pipe(gulp.dest('./dist/assets/fonts'))
});
gulp.task('copy:images', function() {
return gulp.src('./bower_components/path/to/images')
.pipe(gulp.dest('./dist/assets/images'))
});
If you use multiple locations, you can use an array instead of a string for your source files.
gulp.task('copy:images', function() {
return gulp.src([
'./bower_components/module1/path/to/images',
'./bower_components/module2/path/to/images'
])
.pipe(gulp.dest('./dist/assets/images'))
});
To execute your script you run gulp copy:css, gulp copy:fonts, gulp copy:images