Asp.net Core MVC Basic Model
**********************************************
Asp.net Core MVC Basic Model
namespace WebApplication9.Models
{
public class Employee
{
public int EmpID { get; set; }
public string EmpName { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public int Age { get; set; }
}
}
public IActionResult Index() {
List<Employee> EmployeeS = new List<Employee>
//var EmployeeS = new List<Employee>
{ new Employee { EmpID = 1, EmpName = "Varun", Gender = "Male", City = "Agra", Age = 23 }, new Employee { EmpID = 2, EmpName = "Akash", Gender = "Male", City = "Jharkhan", Age = 25 }, new Employee { EmpID = 3, EmpName = "Pravin", Gender = "Male", City = "Delhi", Age = 29 }, new Employee { EmpID = 4, EmpName = "Nilay", Gender = "Male", City = "Noida", Age = 24 } }; return View(EmployeeS);
}
@model List<Employee> @{ ViewData["Title"] = "Home Page"; } <div class="text-center"> <h1 class="display-4">Welcome</h1> <p> Learn about <a href="https://learn.microsoft.com/aspnet/core" target="_blank">building Web apps with ASP.NET Core</a>. </p> </div> <table class="table table-bordered table-striped"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Gender</th> <th>City</th> <th>Age</th> </tr> </thead> <tbody> @foreach (var emp in Model) { <tr> <td>@emp.EmpID</td> <td>@emp.EmpName</td> <td>@emp.Gender</td> <td>@emp.City</td> <td>@emp.Age</td> </tr> } </tbody> </table>**********************************************
Basic Configuration
ASP.NET CORERoute Configurationvar builder = WebApplication.CreateBuilder(args);builder.Services.AddControllersWithViews();var app = builder.Build();//app.MapGet("/", () => "Hello World!");app.MapControllerRoute(name: "default",pattern: "{controller=home}/{action=index}/{id?}");app.Run();*****************************************************************var builder = WebApplication.CreateBuilder(args);// Add services to the containerbuilder.Services.AddControllersWithViews();var app = builder.Build();// Enable static files to serve CSS, JavaScript, and images from wwwroot folderapp.UseStaticFiles();// Configure routing for MVCapp.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");app.Run();HOMECONTROLLER************************************************************using Microsoft.AspNetCore.Mvc;
using LibraLibrary_MVC1.Models;
using LibraLibrary_MVC1.DataContext;
namespace LibraLibrary_MVC1.Controllers
{
public class HomeController : Controller
{
private readonly ApplicationDBContext _context;
public HomeController(ApplicationDBContext context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
public IActionResult Login(LoginViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Check Admin login
var admin = _context.Admins
.FirstOrDefault(a => a.UserName == model.Username && a.Password == model.Password);
if (admin != null)
{
//TempData["UserRole"] = "Admin";
//TempData["UserName"] = admin.Name;
HttpContext.Session.SetString("UserRole", "Admin");
HttpContext.Session.SetString("UserName", admin.Name);
return RedirectToAction("AdminDashboard", "Admin");
}
// Check Student login
var student = _context.Students
.FirstOrDefault(s => s.Email == model.Username && s.Password == model.Password);
if (student != null)
{
HttpContext.Session.SetString("UserRole", "Student");
HttpContext.Session.SetString("UserName", student.FirstName);
return RedirectToAction("Dashboard", "Student");
}
ModelState.AddModelError("", "Invalid username or password");
return View(model);
}
}
}
LOGIN PAGE*****************************************************************************@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers@model LibraLibrary_MVC1.Models.LoginViewModel<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta content="width=device-width, initial-scale=1.0" name="viewport"><title>Libr library Login</title><meta content="" name="description"><meta content="" name="keywords"><!-- Favicons --><link href="~/assets2/img/favicon.png" rel="icon"><link href="~/assets2/img/apple-touch-icon.png" rel="apple-touch-icon"><!-- Google Fonts --><link href="https://fonts.gstatic.com" rel="preconnect"><link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet"><!-- Vendor CSS Files --><link href="~/assets2/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"><link href="~/assets2/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet"><link href="~/assets2/vendor/boxicons/css/boxicons.min.css" rel="stylesheet"><link href="~/assets2/vendor/quill/quill.snow.css" rel="stylesheet"><link href="~/assets2/vendor/quill/quill.bubble.css" rel="stylesheet"><link href="~/assets2/vendor/remixicon/remixicon.css" rel="stylesheet"><link href="~/assets2/vendor/simple-datatables/style.css" rel="stylesheet"><!-- Template Main CSS File --><link href="~/assets2/css/style.css" rel="stylesheet"><!-- =======================================================* Template Name: NiceAdmin - v2.5.0* Template URL: https://bootstrapmade.com/nice-admin-bootstrap-admin-html-template/* Author: BootstrapMade.com* License: https://bootstrapmade.com/license/======================================================== --></head><body><main><div class="container"><section class="section register min-vh-100 d-flex flex-column align-items-center justify-content-center py-4"><div class="container"><div class="row justify-content-center"><div class="col-lg-4 col-md-6 d-flex flex-column align-items-center justify-content-center"><div class="d-flex justify-content-center py-4"><a href="/" class="logo d-flex align-items-center w-auto"><img src="~/assets2/img/logo.png" alt=""><span class="d-none d-lg-block">Libra Library</span></a></div><!-- End Logo --><div class="card mb-3"><div class="card-body"><div class="pt-4 pb-2"><h5 class="card-title text-center pb-0 fs-4">Login to Your Account</h5><p class="text-center small">Enter your username & password to login</p></div><form asp-action="Login" method="post" class="row g-3 needs-validation" novalidate><!-- Validation summary (displays model-level errors) --><div class="col-12"><div asp-validation-summary="All" class="text-danger"></div></div><!-- Username Field --><div class="col-12"><label asp-for="Username" class="form-label">Username</label><div class="input-group has-validation"><input asp-for="Username" id="Username" class="form-control" /><span asp-validation-for="Username" class="text-danger"></span></div></div><!-- Password Field --><div class="col-12"><label asp-for="Password" class="form-label">Password</label><div class="input-group has-validation"><input asp-for="Password" id="Password" class="form-control" type="password" /><span asp-validation-for="Password" class="text-danger"></span></div></div><!-- Remember Me --><div class="col-12"><div class="form-check"><input class="form-check-input" type="checkbox" name="remember" value="true" id="rememberMe"><label class="form-check-label" for="rememberMe">Remember me</label></div></div><!-- Submit Button --><div class="col-12"><button class="btn btn-primary w-100" type="submit">Login</button></div><!-- Register Link --><div class="col-12"><p class="small mb-0">Don't have an account? <a href="pages-register.html">Create one</a></p></div></form>@* <form asp-action="Login" method="post" class="row g-3 needs-validation" novalidate><div class="col-12"><label asp-for="Username" class="form-label">Username</label><div class="input-group has-validation"><input asp-for="Username" class="form-control" /><span asp-validation-for="Username" class="text-danger"></span></div></div><div class="col-12"><label asp-for="Password" class="form-label">Password</label><input asp-for="Password" class="form-control" type="password" /><span asp-validation-for="Password" class="text-danger"></span></div><div class="col-12"><div class="form-check"><input class="form-check-input" type="checkbox" name="remember" value="true" id="rememberMe"><label class="form-check-label" for="rememberMe">Remember me</label></div></div><div class="col-12"><button class="btn btn-primary w-100" type="submit" >Login</button></div><div class="col-12"><p class="small mb-0">Don't have an account? <a href="pages-register.html">Create one</a></p></div></form> *@</div></div><div class="credits">@* Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a> *@</div></div></div></div></section></div></main><!-- End #main --><a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a><!-- Vendor JS Files --><script src="~/assets2/vendor/apexcharts/apexcharts.min.js"></script><script src="~/assets2/vendor/bootstrap/js/bootstrap.bundle.min.js"></script><script src="~/assets2/vendor/chart.js/chart.umd.js"></script><script src="~/assets2/vendor/echarts/echarts.min.js"></script><script src="~/assets2/vendor/quill/quill.min.js"></script><script src="~/assets2/vendor/simple-datatables/simple-datatables.js"></script><script src="~/assets2/vendor/tinymce/tinymce.min.js"></script><script src="~/assets2/vendor/php-email-form/validate.js"></script><!-- Template Main JS File --><script src="~/assets2/js/main.js"></script></body></html>LOGINVIEWMODEL********************************************************************using System.ComponentModel.DataAnnotations;namespace LibraLibrary_MVC1.Models{public class LoginViewModel{[Required(ErrorMessage = "Username is required")]public string Username { get; set; }[Required(ErrorMessage = "Password is required")]public string Password { get; set; }}}APLICATIONDBCONTEXT*************************************************************using LibraLibrary_MVC1.Models;using Microsoft.EntityFrameworkCore;namespace LibraLibrary_MVC1.DataContext{public class ApplicationDBContext : DbContext{public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options){}public DbSet<Admin> Admins { get; set; }public DbSet<Student> Students { get; set; }}}ADMINCONTROLLER*****************************************************using Microsoft.AspNetCore.Mvc;namespace LibraLibrary_MVC1.Controllers{public class AdminController : Controller{public IActionResult Index(){return View();}public IActionResult AdminDashboard(){return View();}}}PROGRAMME.CS*************************************************************using LibraLibrary_MVC1.DataContext;using Microsoft.EntityFrameworkCore;var builder = WebApplication.CreateBuilder(args);//var connectionString = builder.Configuration.GetConnectionString("LibraConnection");// ❗ Register services BEFORE building the appbuilder.Services.AddControllersWithViews();builder.Services.AddDbContext<ApplicationDBContext>(options =>options.UseSqlServer(builder.Configuration.GetConnectionString("LibraConnection")));//builder.Services.AddDbContext<ApplicationDBContext>(options =>// options.UseSqlServer("LibraConnection")//);builder.Services.AddSession(options =>{options.IdleTimeout = TimeSpan.FromMinutes(30); // Set session timeoutoptions.Cookie.HttpOnly = true;options.Cookie.IsEssential = true;});// ❗ Now build the appvar app = builder.Build();// Middleware pipelineapp.UseStaticFiles();app.UseRouting();app.UseHttpsRedirection();app.UseSession();//app.UseAuthentication();//app.UseAuthorization();app.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");app.Run();
No comments:
Post a Comment