Cannot show razor view in browser (ASP.NET Core MVC) - razor

I am really new to this ASP.NET Core MVC stuff I have this problem: browser is showing "Page not found 404" error.
Here is my code:
Model class (inside Models folder):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.AspNetCore.Http;
using System.ComponentModel;
namespace CasaSelectaAppWeb.Models
{
public class HabitatClass
{
[Key]
[StringLength(100)]
public string CodeHab { get; set; }
[Required]
[StringLength(30)]
public string DesignationHab { get; set; }
[Required]
public int Superficie { get; set; }
[Required]
[Range (1,40)]
public int NbrPieces { get; set; }
[Required]
[DisplayName("Prix Initial")]
[RegularExpression("([1-9][0-9]*)", ErrorMessage = "Veuillez entrer une valeur correcte !")]
public int prixInit { get; set; }
[Required]
[DisplayName("Prix négotcié")]
[RegularExpression("([1-9][0-9]*)", ErrorMessage = "Veuillez entrer une valeur correcte !")]
public int prixNego { get; set; }
[Required]
[StringLength(20)]
public string LocalHab { get; set; }
[Required]
[StringLength(200)]
public string AdressHab { get; set; }
[Required]
[StringLength(400)]
public string DescriptionHab { get; set; }
[MaxLength]
//public byte[] ImageUrl { get; set; }
//[Required(ErrorMessage ="Veuillez ajouter une image !")]
//[Display(Name ="Image")]
//[NotMapped]
//public IFormFile ImageHab { get; set; }
//CleEtrngVente
[Display(Name ="Type d'habitat")]
[StringLength(30)]
public virtual string TypeHpk { get; set; }
[ForeignKey("TypeHpk")]
public virtual TypeHabitat TypesHab { get; set; }
}
}
Html markup:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - CasaSelectaAppWeb</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">CasaSelectaAppWeb</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="CasaSelecta" asp-action="Index">Liste des habitats</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
#RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2022 - CasaSelectaAppWeb - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
#await RenderSectionAsync("Scripts", required: false)
</body>
</html>
Controller
using CasaSelectaAppWeb.Data;
using CasaSelectaAppWeb.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CasaSelectaAppWeb.Controllers
{
public class HabitatsController : Controller
{
private readonly DbContClass _context;
public HabitatsController(DbContClass context)
{
_context = context;
}
public IActionResult Index()
{
List<HabitatClass> habitats;
habitats = _context.Habitats.ToList();
return View(habitats);
}
}
}

1.check you have configured routing in startup.cs:
app.UseRouting();
...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
2.Check if your routing exists.For example,routing of Index in your code is
https://localhost:xxx/Habitats/Index
3.Check if your corresponding view is in the correct location.For example the view of Index should in Views/Habitats,and the name should be Index.cshtml.

Related

ASP.NET Core how can I link the front end to the back end?

Ok so the purpose of my project is to have files uploaded to a site. I have done that through relative path mapping. Now I have added a navigation menu, 1 for the admin and 1 for the user. I want to have a file uploaded (by the admin) to a certain category (as of now, they are displayed in a single category using listing) so that the user will have to click that certain category in order to see that specific file. How do I do that?
This is my razor page :
#if (User.IsInRole("Admin"))
{
<!-- In order to post files to server we should use form with post method, also need to add multipart/form-data encoding.
Otherwise the files will not sent to the server. -->
<form method="post" enctype="multipart/form-data" id="catform">
<input asp-for="Files" type="file" name="files" multiple />
<button type="submit">Upload</button>
</form>
<p>Alegeti categoria de personal pentru care doriti sa uploadati</p>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Alegeti categoria
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Incepatori</a>
<a class="dropdown-item" href="#">Avansati</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Admini</a>
</div>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
}
#if (User.IsInRole("User"))
{
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Incepatori</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Avansati</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Admini</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
}
public IActionResult Index1()
{
// Get files from the server
var model = new FilesViewModel();
foreach (var item in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "upload")))
{
model.Files.Add(
new FileDetails { Name = System.IO.Path.GetFileName(item), Path = item });
}
return View(model);
}
[HttpPost]
public IActionResult Index1(IFormFile[] files)
{
// Iterate each files
foreach (var file in files)
{
// Get the file name from the browser
var fileName = System.IO.Path.GetFileName(file.FileName);
// Get file path to be uploaded
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "upload", fileName);
// Check If file with same name exists and delete it
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
// Create a new local file and copy contents of uploaded file
using (var localFile = System.IO.File.OpenWrite(filePath))
using (var uploadedFile = file.OpenReadStream())
{
uploadedFile.CopyTo(localFile);
}
}
ViewBag.Message = "Files are successfully uploaded";
// Get files from the server
var model = new FilesViewModel();
foreach (var item in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "upload")))
{
model.Files.Add(
new FileDetails { Name = System.IO.Path.GetFileName(item), Path = item });
}
return View(model);
}
This 2 methods in my controller which are used to list and download files in wwwroot/upload folder in my project.
public IActionResult files() {
string[] filePaths = Directory.GetFiles(Path.Combine(_hostingEnvironment.WebRootPath, "upload/"));
List<MyFile> files = new List<MyFile>();
foreach (string filePath in filePaths)
{
files.Add(new MyFile { filename = Path.GetFileName(filePath) });
}
return View(files);
}
public IActionResult DownloadFile(string fileName)
{
string path = Path.Combine(_hostingEnvironment.WebRootPath, "upload/") + fileName;
byte[] bytes = System.IO.File.ReadAllBytes(path);
return File(bytes, "text/plain", fileName);
}
And this is my view page code:
#model List<WebApplication2.Models.MyFile>
<table>
<tr>
<th>File Name</th>
<th></th>
</tr>
#foreach (MyFile file in Model)
{
<tr>
#*<td>#file.filename</td>*#
<td>#Html.ActionLink(#file.filename, "DownloadFile", new { fileName = file.filename })</td>
</tr>
}
</table>

Attribute name cannot be null or empty.ThemeLeaf isue with Spring

I was trying to integrate spring project with admin dashboard template using themeleaf.However when I tried to run the project following issues have been displayed:
An error happened during template parsing (template: "class path resource [templates/index.html]")
Caused by: java.lang.IllegalArgumentException: Attribute name cannot be null or empty
I used themeleaf link for my html and wrote controller to run the app properly.However,despite the changes I made there were no result.
DashBoardController.java
package io.javabrains.Dashboard;
import java.util.Date;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
public class DashboardController {
private static final String appName = "ThymeleafTour";
#GetMapping("/")
public String home(Model model,
#RequestParam(value = "name", required = false,
defaultValue = "Guest") String name) {
model.addAttribute("name", name);
model.addAttribute("title", appName);
return "home";
}
}
build.gradle
plugins {
id 'org.springframework.boot' version '1.5.8.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
group = 'io.javabrains.com'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-web-services'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'mysql:mysql-connector-java'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title th:text:="${title}">
<!-- Custom fonts for this template-->
<link href= "#" th:href="#{/vendor/fontawesome-free/css/all.min.css}" rel="stylesheet" type="text/css"/>
<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"/>
<!-- Custom styles for this template-->
<link href="#" th:href="#{//css/sb-admin-2.min.css}" rel="stylesheet"/>
</head>
<body id="page-top">
<!-- Page Wrapper -->
<div id="wrapper">
<!-- Sidebar -->
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<!-- Sidebar - Brand -->
<a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html">
<div class="sidebar-brand-icon rotate-n-15">
<i class="fas fa-laugh-wink"></i>
</div>
<h1 th:text="|Hello ${name}!|"></h1>
</a>
<!-- Divider -->
<hr class="sidebar-divider my-0">
<!-- Nav Item - Dashboard -->
<li class="nav-item active">
<a class="nav-link" href="index.html">
<i class="fas fa-fw fa-tachometer-alt"></i>
<span>Dashboard</span></a>
</li>
<!-- Divider -->
<hr class="sidebar-divider">
<!-- Heading -->
<div class="sidebar-heading">
Interface
</div>
<!-- Nav Item - Pages Collapse Menu -->
<li class="nav-item">
<a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
<i class="fas fa-fw fa-cog"></i>
<span>Components</span>
</a>
<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Custom Components:</h6>
<a class="collapse-item" href="buttons.html">Buttons</a>
<a class="collapse-item" href="cards.html">Cards</a>
</div>
</div>
</li>
With these codes I think project must work well without errors.However the same errors in console keeps displaying

Spring - How to display submenu in all URLs

i'm using spring boot + thymeleaf, i devided all fragment as header, footer, ...
this is my header
<div th:fragment="header" th:remove="tag">
<!--header-->
<div class="logo">
<div class="container">
<div class="logo-info">
<a href="index.html">
<h1>Logo</h1>
<!-- <span class="glyphicon glyphicon-grain" aria-hidden="true"></span> -->
</a>
</div>
</div>
</div>
<!--//header-->
<!--navigation-->
<div class="top-nav">
<nav class="navbar navbar-default">
<div class="container">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">Menu</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="hvr-bounce-to-bottom active">Home</li>
<li class="hvr-bounce-to-bottom">About</li>
<li>Gallery<span class="caret"></span>
<ul class="dropdown-menu" th:each="category: ${listCategory}">
<li><a class="hvr-bounce-to-bottom" th:href="#{/category/${category.getId()} } " th:text="${category.getName()}"></a></li>
</ul></li>
<li class="hvr-bounce-to-bottom">Short Codes</li>
<li class="hvr-bounce-to-bottom">Contact Us</li>
</ul>
<div class="clearfix"></div>
</div>
</nav>
</div>
<!--//navigation-->
</div>
This is picture
this is picture for example
i want to display data from mysql to 'Gallery' menu (Gallery1, Gallery2, Gallery3)
so when i go to my website, all URLs will show submenu in 'Gallery'
UPDATE: this is controller
#Controller
public class CategoryController {
#Autowired
private CategoryService categoryService;
#RequestMapping(value = "/category/{id}")
public String getCategoryByID(Model model, #PathVariable(name = "id") Long id) {
List<CategoryDTO> categoryDTOs = categoryService.getAllCategory();
model.addAttribute("listCategory", categoryDTOs);
return "common/header";
}
}
I'm new to Spring and Thymeleaf also, but try to do an Repository
public interface CategoryRepository extends
JpaRepository<CategoryDTO, String>{
}
Controller:
#Controller
public class CategoryController {
#Autowired
private categoryRepository categoryRepository;
#RequestMapping(value = "/category")
public String getCategoryByID(Model model) {
List<CategoryDTO> categoryDTOs =
categoryRepository.findAll();
model.addAttribute("listCategory", categoryDTOs);
return "common/header";
}
}
And in Thymeleaf try to do something like this:
category: ${listCategory}" th:value=" ${file.fileName}"
<li><a class="hvr-bounce-to-bottom"
th:value="${category.getName()}"></a></li>

collapsible navbar will not work (using bootstrap)

I have been working with this for awhile. The navbar shows up just fine, but the functionality is not there. Here is the code:
<nav class = "navbar navbar-inverse navbar-fixed-top" role = "navigation" id = "my-navbar">
<div class = "container">
<div class = "navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-ex1-collapse" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
</button>
<a class = "navbar-brand" href = "index.html">WM</a>
</div>
<div class = "collapse navbar-collapse" id = "myNavbar">
<ul class = "nav navbar-nav navbar-right">
<li>Projects</li>
<li>Resume</li>
<li>Contact Me</li>
<input type = "button" class="btn btn-info navbar-btn" value = "Blog" onclick = "relocate_blog()" id = "blog-button">
<script>
function relocate_blog() {
location.href = "blog.html ";
}
</script>
</ul>
</div>
</div>
<!--End Container -->
</nav>
<!-- End Navbar -->
<nav class = "navbar navbar-inverse navbar-fixed-top" role = "navigation">
<div class = "container">
<div class = "navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
</button>
<a class = "navbar-brand" href = "index.html">WM</a>
</div>
<div class = "collapse navbar-collapse" id = "myNavbar">
<ul class = "nav navbar-nav navbar-right">
<li>Projects</li>
<li>Resume</li>
<li>Contact Me</li>
<input type = "button" class="btn btn-info navbar-btn" value = "Blog" onclick = "relocate_blog()" id = "blog-button">
<script>
function relocate_blog() {
location.href = "blog.html ";
}
</script>
</ul>
</div>
</div><!--End Container -->
</nav><!-- End Navbar -->

Navigation bar not working in small screen

I have created a simple navigation bar using bootstrap but when i click on it ,it does not show the list items ,it works fine in bigger screen.
I have tried many alternatives but it does not work.
<html>
<head>
<meta charset = "utf8">
<meta http-equiv = "X-UA-Compatible" content = "IE = edge">
<meta name = "viewport" content = "width = device-width initial-scale = 1">
<link rel = "stylesheet" type = "text/css" href = "conFusion/css/bootstrap.min.css">
<link rel = "stylesheet" type = "text/css" href = "conFusion/css/bootstrap-theme.min.css">
</head>
<body>
<nav class = "navbar navbar-inverse" role = "navigation">
<div class = "container">
<div class = "navbar-header">
<button type = "button" class = "navbar-toggle collapsed"
data-toggle = "collapse" data-target = "#navbar" area-controls = "navbar"
aria-expanded="false">
<span class = "sr-only">Toggle Navigation</span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
</button>
<a class = "navbar-brand">Indore Medical</a>
</div>
<div id = "navbar" class = "navbar-collapse collapse">
<ul class = "nav navbar-nav">
<li class = "active">Main-Course</li>
<li>Starters</li>
<li>Desert</li>
<li>About-us</li>
</ul>
</div>
</div>
</nav>
</body>
</html>
Considering your provided code, it seems that you haven't included jQuery library file and Bootstrap's JavaScript requires jQuery to run its JS/jQ events like toggle menu etc.
Code Snippet
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<nav class="navbar navbar-inverse" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" area-controls="navbar" aria-expanded="false">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand">Indore Medical</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active">Main-Course
</li>
<li>Starters
</li>
<li>Desert
</li>
<li>About-us
</li>
</ul>
</div>
</div>
</nav>