ASP.net Program
ASP.net Program
➔Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;
namespace MyProject.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
}
➔Views/Home/Index.cshtml
@{
ViewData["Title"] = "Display Name and Address";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>@ViewData["Title"]</title>
<link rel="stylesheet" href="/styles.css" />
</head>
1
<body>
<div class="container">
<h1>Your Details</h1>
<div class="info-box">
<p><span class="label">Name:</span> John Doe</p>
<p><span class="label">Address:</span> 1234 Elm Street,
Springfield, IL 62704</p>
</div>
</div>
</body>
</html>
➔wwwroot/styles.css
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
text-align: center;
width: 300px;
}
2
h1 {
font-size: 20px;
margin-bottom: 15px;
color: #333;
}
p{
font-size: 14px;
margin: 5px 0;
color: #555;
}
.label {
font-weight: bold;
}
➔Models/PhonebookEntry.cs
using System.ComponentModel.DataAnnotations;
namespace YourNamespace.Models
{
public class PhonebookEntry
{
public int No { get; set; }
[Required]
public string Name { get; set; }
3
[Required]
public string City { get; set; }
[Required]
[Phone]
public string Phone { get; set; }
}
}
➔Views/Home/Index.cshtml
@model List<YourNamespace.Models.PhonebookEntry>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0" />
<title>Phonebook</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bo
otstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container mt-5">
<h1 class="text-center">Phonebook</h1>
<table class="table table-bordered mt-4">
<thead class="table-dark">
<tr>
<th>No</th>
4
<th>Name</th>
<th>City</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
@foreach (var entry in Model)
{
<tr>
<td>@entry.No</td>
<td>@entry.Name</td>
<td>@entry.City</td>
<td>@entry.Phone</td>
</tr>
}
</tbody>
</table>
</div>
</body>
</html>
➔Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;
using YourNamespace.Models;
using System.Collections.Generic;
namespace YourNamespace.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
5
// Sample data for the phonebook
var phonebook = new List<PhonebookEntry>
{
new PhonebookEntry { No = 1, Name = "Alice Johnson",
City = "New York", Phone = "123-456-7890" },
new PhonebookEntry { No = 2, Name = "Bob Smith", City
= "Los Angeles", Phone = "987-654-3210" },
new PhonebookEntry { No = 3, Name = "Charlie Brown",
City = "Chicago", Phone = "555-123-4567" },
new PhonebookEntry { No = 4, Name = "David Wilson",
City = "Houston", Phone = "444-555-6666" },
new PhonebookEntry { No = 5, Name = "Emma Watson",
City = "Phoenix", Phone = "333-444-5555" },
new PhonebookEntry { No = 6, Name = "Franklin Green",
City = "San Antonio", Phone = "222-333-4444" },
new PhonebookEntry { No = 7, Name = "Grace Hall", City
= "San Diego", Phone = "111-222-3333" },
new PhonebookEntry { No = 8, Name = "Hannah Moore",
City = "Dallas", Phone = "999-888-7777" },
new PhonebookEntry { No = 9, Name = "Ian Clark", City =
"San Jose", Phone = "666-777-8888" },
new PhonebookEntry { No = 10, Name = "Jack Taylor",
City = "Austin", Phone = "555-666-7777" }
};
return View(phonebook);
}
}
}
6
3. DAW a display friendbook wth following fields and 5
rocord field id name city phone.
➔Friend.cs (Model)
public class Friend
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Phone { get; set; }
}
➔FriendbookController.cs
using System.Collections.Generic;
using System.Web.Mvc;
using YourProject.Models;
namespace YourProject.Controllers
{
public class FriendbookController : Controller
{
// Sample data for the Friendbook
public ActionResult Index()
{
var friends = new List<Friend>
{
new Friend { Id = 1, Name = "John Doe", City = "New
York", Phone = "123-456-7890" },
new Friend { Id = 2, Name = "Jane Smith", City = "Los
Angeles", Phone = "987-654-3210" },
7
new Friend { Id = 3, Name = "Michael Johnson", City =
"Chicago", Phone = "555-555-5555" },
new Friend { Id = 4, Name = "Emily Davis", City =
"Houston", Phone = "444-444-4444" },
new Friend { Id = 5, Name = "Daniel Brown", City =
"Phoenix", Phone = "333-333-3333" }
};
return View(friends);
}
}
}
➔Index.cshtml (View)
@model IEnumerable<YourProject.Models.Friend>
@{
ViewBag.Title = "Friendbook";
}
<h2>Friendbook</h2>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>City</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
8
@foreach (var friend in Model)
{
<tr>
<td>@friend.Id</td>
<td>@friend.Name</td>
<td>@friend.City</td>
<td>@friend.Phone</td>
</tr>
}
</tbody>
</table>
.name-style-2 {
color: #33b5ff; /* Blue */
font-size: 28px;
font-family: 'Arial', sans-serif;
}
.name-style-3 {
color: #33cc33; /* Green */
9
font-size: 30px;
font-style: italic;
}
.name-style-4 {
color: #f1c40f; /* Yellow */
font-size: 26px;
text-transform: uppercase;
}
.name-style-5 {
color: #8e44ad; /* Purple */
font-size: 32px;
text-decoration: underline;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>@ViewData["Title"]</title>
<link href="~/css/styles.css" rel="stylesheet" />
</head>
<body>
<div class="container">
10
<h1>Display Your Name in Different Styles</h1>
➔Controller (Controllers/HomeController.cs)
using Microsoft.AspNetCore.Mvc;
namespace YourProject.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
}
11
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
➔Index.cshtml
@{
ViewBag.Title = "Home Page";
}
<p>
This is an example of using TextMode with ASP.NET MVC.
</p>
➔HomeController.cs
using System.Web.Mvc;
12
namespace YourNamespace.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
➔Model (Phonebook.cs)
public class Phonebook
{
public int Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public string ImageUrl { get; set; }
}
13
➔HomeController.cs
using System.Collections.Generic;
using System.Web.Mvc;
using YourNamespace.Models; // Replace with actual namespace
return View(phonebookList);
}
}
14
➔Index.cshtml (View)
@model IEnumerable<YourNamespace.Models.Phonebook> <!--
Replace with actual namespace -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Phonebook</title>
<link rel="stylesheet" href="~/Content/styles.css"> <!-- Include
your CSS file -->
</head>
<body>
<h2>Phonebook</h2>
<table>
<thead>
<tr>
<th>Photo</th>
<th>Name</th>
<th>Phone Number</th>
</tr>
</thead>
<tbody>
@foreach (var contact in Model)
{
<tr>
<td><img src="@contact.ImageUrl"
alt="@contact.Name" style="width:50px; height:50px; border-
radius:50%"></td>
<td>@contact.Name</td>
15
<td>@contact.PhoneNumber</td>
</tr>
}
</tbody>
</table>
</body>
</html>
➔styles.css
table {
width: 80%;
margin: 20px auto;
border-collapse: collapse;
}
th, td {
padding: 10px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
img {
border-radius: 50%;
}
16
7. Design a small Project with page navigation using
response redirect command ( Page ) ( Student list ) ( Phone
Book with photo ) ( resultsheet ) ( about us )
➔HomeController.cs
using Microsoft.AspNetCore.Mvc;
namespace YourProjectName.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View(); // Home page with links to other pages
}
17
return RedirectToAction("Index", "ResultSheet"); //
Redirect to result sheet page
}
➔StudentList.cshtml
@{
ViewData["Title"] = "Student List";
}
<h2>Student List</h2>
<ul>
<li>Student 1 - John Doe</li>
<li>Student 2 - Jane Smith</li>
<li>Student 3 - Michael Johnson</li>
<li>Student 4 - Emily Davis</li>
</ul>
➔PhoneBook.cshtml
@{
ViewData["Title"] = "Phone Book";
}
<h2>Phone Book</h2>
<div>
18
<img src="path-to-photo.jpg" alt="Person's Photo" />
<p>John Doe - Phone: 123-456-7890</p>
</div>
<div>
<img src="path-to-photo.jpg" alt="Person's Photo" />
<p>Jane Smith - Phone: 987-654-3210</p>
</div>
<!-- Add more entries as needed -->
➔ResultSheet.cshtml
@{
ViewData["Title"] = "Result Sheet";
}
<h2>Result Sheet</h2>
<table>
<tr>
<th>Subject</th>
<th>Marks</th>
</tr>
<tr>
<td>Mathematics</td>
<td>85</td>
</tr>
<tr>
<td>English</td>
<td>90</td>
</tr>
<tr>
<td>Science</td>
<td>88</td>
</tr>
19
</table>
➔AboutUs.cshtml
@{
ViewData["Title"] = "About Us";
}
<h2>About Us</h2>
<p>We are an educational institution providing top-quality
learning.</p>
<p>Our goal is to provide a comprehensive curriculum that
prepares students for success in their careers.</p>
<ul>
<li><a href="/Home/StudentList">Student List</a></li>
<li><a href="/Home/PhoneBook">Phone Book</a></li>
<li><a href="/Home/ResultSheet">Result Sheet</a></li>
<li><a href="/Home/AboutUs">About Us</a></li>
</ul>
20
➔Database Schema
CREATE DATABASE School;
USE School;
21
-- Student Result Table
CREATE TABLE StudentResult (
ResultID INT PRIMARY KEY IDENTITY(1,1),
StudentID INT,
Subject VARCHAR(100),
MarksObtained INT,
TotalMarks INT,
FOREIGN KEY (StudentID) REFERENCES
StudentMaster(StudentID)
);
➔StudentMaster.cs
public class StudentMaster
{
public int StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
}
➔FeesMaster.cs
public class FeesMaster
{
public int FeeID { get; set; }
public string FeeType { get; set; }
public decimal Amount { get; set; }
public DateTime DueDate { get; set; }
}
22
➔PhoneBook.cs
public class PhoneBook
{
public int PhoneBookID { get; set; }
public int StudentID { get; set; }
public string PhoneNumber { get; set; }
}
➔StudentResult.cs
public class StudentResult
{
public int ResultID { get; set; }
public int StudentID { get; set; }
public string Subject { get; set; }
public int MarksObtained { get; set; }
public int TotalMarks { get; set; }
}
➔HomeController.cs
using System.Linq;
using System.Web.Mvc;
using YourNamespace.Models;
namespace YourNamespace.Controllers
{
public class HomeController : Controller
{
private SchoolDbContext db = new SchoolDbContext();
return View();
}
}
}
➔Index.cshtml
@{
ViewBag.Title = "School Management - Home";
}
<h2>Student List</h2>
<table class="table">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Date of Birth</th>
<th>Gender</th>
<th>Address</th>
</tr>
</thead>
24
<tbody>
@foreach (var student in ViewBag.Students)
{
<tr>
<td>@student.FirstName</td>
<td>@student.LastName</td>
<td>@student.DateOfBirth.ToShortDateString()</td>
<td>@student.Gender</td>
<td>@student.Address</td>
</tr>
}
</tbody>
</table>
<h2>Fees List</h2>
<table class="table">
<thead>
<tr>
<th>Fee Type</th>
<th>Amount</th>
<th>Due Date</th>
</tr>
</thead>
<tbody>
@foreach (var fee in ViewBag.Fees)
{
<tr>
<td>@fee.FeeType</td>
<td>@fee.Amount</td>
<td>@fee.DueDate.ToShortDateString()</td>
</tr>
}
25
</tbody>
</table>
<h2>Phone Book</h2>
<table class="table">
<thead>
<tr>
<th>Student Name</th>
<th>Phone Number</th>
</tr>
</thead>
<tbody>
@foreach (var entry in ViewBag.PhoneBookEntries)
{
<tr>
<td>@ViewBag.Students.FirstOrDefault(s => s.StudentID
== entry.StudentID)?.FirstName</td>
<td>@entry.PhoneNumber</td>
</tr>
}
</tbody>
</table>
<h2>Student Results</h2>
<table class="table">
<thead>
<tr>
<th>Student Name</th>
<th>Subject</th>
<th>Marks Obtained</th>
<th>Total Marks</th>
</tr>
26
</thead>
<tbody>
@foreach (var result in ViewBag.Results)
{
<tr>
<td>@ViewBag.Students.FirstOrDefault(s => s.StudentID
== result.StudentID)?.FirstName</td>
<td>@result.Subject</td>
<td>@result.MarksObtained</td>
<td>@result.TotalMarks</td>
</tr>
}
</tbody>
</table>
➔SchoolDbContext.cs
using System.Data.Entity;
namespace YourNamespace.Models
{
public class SchoolDbContext : DbContext
{
public SchoolDbContext() :
base("name=SchoolDbConnection")
{
}
User.cs:
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public DateTime CreatedAt { get; set; }
}
Product.cs:
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Description { get; set; }
}
Order.cs:
public class Order
{
public int OrderId { get; set; }
public int UserId { get; set; }
public int ProductId { get; set; }
public DateTime OrderDate { get; set; }
public string Status { get; set; }
28
Payment.cs:
public class Payment
{
public int PaymentId { get; set; }
public int OrderId { get; set; }
public decimal Amount { get; set; }
public DateTime PaymentDate { get; set; }
public string PaymentStatus { get; set; }
➔HomeController.cs
using System;
using System.Linq;
using System.Web.Mvc;
using YourProjectNamespace.Models;
namespace YourProjectNamespace.Controllers
{
public class HomeController : Controller
{
private ApplicationDbContext db = new
ApplicationDbContext();
return View();
}
29
private void AddSampleData()
{
// Add Users
for (int i = 1; i <= 10; i++)
{
db.Users.Add(new User
{
Name = "User " + i,
Email = "user" + i + "@example.com",
CreatedAt = DateTime.Now
});
}
// Add Products
for (int i = 1; i <= 10; i++)
{
db.Products.Add(new Product
{
Name = "Product " + i,
Price = 10.99m + i,
Description = "Description for Product " + i
});
}
// Add Orders
for (int i = 1; i <= 10; i++)
{
db.Orders.Add(new Order
{
UserId = i,
ProductId = i,
30
OrderDate = DateTime.Now,
Status = "Pending"
});
}
// Add Payments
for (int i = 1; i <= 10; i++)
{
db.Payments.Add(new Payment
{
OrderId = i,
Amount = 10.99m + i,
PaymentDate = DateTime.Now,
PaymentStatus = "Completed"
});
}
db.SaveChanges();
}
}
}
➔Index.cshtml
@{
ViewBag.Title = "Home Page";
}
31
➔ApplicationDbContext.cs
using System.Data.Entity;
namespace YourProjectNamespace.Models
{
public class ApplicationDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Payment> Payments { get; set; }
}
}
➔HomeController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
32
using YourProjectNamespace.Data; // Adjust for your project
namespace
using YourProjectNamespace.Models;
[HttpPost]
public IActionResult UpdateRecords(List<MyModel> models)
{
if (models != null && models.Any())
{
foreach (var model in models)
{
var record1 = _context.Table1.FirstOrDefault(r => r.Id ==
model.Id);
var record2 = _context.Table2.FirstOrDefault(r => r.Id ==
model.Id);
var record3 = _context.Table3.FirstOrDefault(r => r.Id ==
model.Id);
var record4 = _context.Table4.FirstOrDefault(r => r.Id ==
model.Id);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(models);
}
➔Index.cshtml
@model List<MyModel>
➔ HomeController.cs
35
using System.Web.Mvc;
using YourProjectNamespace.Models; // Adjust the namespace as
needed
namespace YourProjectNamespace.Controllers
{
public class HomeController : Controller
{
private ApplicationDbContext db = new
ApplicationDbContext(); // Your DB context
36
return RedirectToAction("Index"); // Redirect to another
page, such as home
}
catch (Exception ex)
{
// Handle exceptions
ViewBag.ErrorMessage = "An error occurred: " +
ex.Message;
return View("Error");
}
}
}
}
➔ DeleteAllRecords.cshtml
@{
ViewBag.Title = "Delete All Records";
}
<p>Are you sure you want to delete all records from the
database? This action cannot be undone.</p>
37
<form method="post" action="@Url.Action("DeleteAllRecords",
"Home")">
<button type="submit" class="btn btn-danger">Delete All
Records</button>
</form>
➔ .cs File
using Microsoft.EntityFrameworkCore;
namespace YourNamespace
{
public class YourDbContext : DbContext
{
public DbSet<YourModel> YourModels { get; set; }
<h2>Drop Table</h2>
➔ HomeController.cs
using Microsoft.AspNetCore.Mvc;
using YourNamespace;
namespace YourNamespace.Controllers
{
public class HomeController : Controller
{
private readonly YourDbContext _context;
[HttpPost]
public IActionResult DropTable()
{
_context.DropTable();
return RedirectToAction("Index");
}
39
public IActionResult Index()
{
return View();
}
}
}
[HttpPost]
public IActionResult DeleteDatabase()
{
try
{
using (SqlConnection connection = new
SqlConnection(connectionString))
{
40
connection.Open();
string query = "DROP DATABASE YourDatabaseName"; //
Replace with your actual database name
SqlCommand command = new SqlCommand(query,
connection);
command.ExecuteNonQuery();
ViewData["Message"] = "Database deleted
successfully!";
}
}
catch (Exception ex)
{
ViewData["Error"] = "An error occurred: " + ex.Message;
}
return View("Index");
}
}
➔ Index.cshtml
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Delete Database</h1>
<form method="post" asp-action="DeleteDatabase">
<button type="submit" class="btn btn-danger">Delete
Database</button>
</form>
<div>
@if (ViewData["Message"] != null)
41
{
<p class="text-success">@ViewData["Message"]</p>
}
@if (ViewData["Error"] != null)
{
<p class="text-danger">@ViewData["Error"]</p>
}
</div>
</div>
➔ HomeController.cs
using Microsoft.AspNetCore.Mvc;
using YourNamespace.Models;
namespace YourNamespace.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
// Creating the model data
42
HomeModel model = new HomeModel
{
Title = "Welcome to My Simple Website",
Message = "This is a simple MVC page with a controller,
model, and view."
};
return View(model);
}
}
}
➔ Index.cshtml
@model YourNamespace.Models.HomeModel
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>@Model.Title</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bo
otstrap.min.css">
</head>
<body>
<div class="container">
<h1 class="my-5">@Model.Title</h1>
<p>@Model.Message</p>
<a href="#" class="btn btn-primary">Learn More</a>
</div>
43
</body>
</html>
➔ Startup Configuration:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});}
44
15. Make Tbale with given fiels name enater 10 reocrd in
int (Field data type size )
➔ Record.cs
using System.ComponentModel.DataAnnotations;
namespace YourProject.Models
{
public class Record
{
[Key]
public int Id { get; set; }
➔ ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
namespace YourProject.Data
{
public class ApplicationDbContext : DbContext
45
{
public
ApplicationDbContext(DbContextOptions<ApplicationDbContext>
options)
: base(options)
{
}
➔ HomeController.cs
using Microsoft.AspNetCore.Mvc;
using YourProject.Data;
using YourProject.Models;
namespace YourProject.Controllers
{
public class HomeController : Controller
{
private readonly ApplicationDbContext _context;
➔ Index.cshtml
@model IEnumerable<YourProject.Models.Record>
<!DOCTYPE html>
<html lang="en">
47
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Records</title>
</head>
<body>
<h1>Record List</h1>
<table>
<thead>
<tr>
<th>Id</th>
<th>Field1</th>
<th>Field2</th>
<th>Field3</th>
<th>Field4</th>
<th>Field5</th>
<th>Field6</th>
<th>Field7</th>
<th>Field8</th>
<th>Field9</th>
<th>Field10</th>
</tr>
</thead>
<tbody>
@foreach (var record in Model)
{
<tr>
<td>@record.Id</td>
<td>@record.Field1</td>
<td>@record.Field2</td>
<td>@record.Field3</td>
48
<td>@record.Field4</td>
<td>@record.Field5</td>
<td>@record.Field6</td>
<td>@record.Field7</td>
<td>@record.Field8</td>
<td>@record.Field9</td>
<td>@record.Field10</td>
</tr>
}
</tbody>
</table>
</body>
</html>
49
INSERT INTO StudentResults (FirstName, LastName, DateOfBirth,
Subject, MarksObtained, TotalMarks, Result)
VALUES
('John', 'Doe', '2000-01-01', 'Math', 80, 100, 'Pass'),
('Jane', 'Smith', '2001-02-15', 'English', 70, 100, 'Pass'),
('Mike', 'Johnson', '1999-07-20', 'History', 60, 100, 'Pass'),
('Emily', 'Davis', '2000-03-25', 'Math', 85, 100, 'Pass'),
('James', 'Brown', '2002-05-10', 'Science', 45, 100, 'Fail'),
('Anna', 'Wilson', '2001-11-12', 'Geography', 90, 100, 'Pass'),
('David', 'Taylor', '1998-06-17', 'Math', 95, 100, 'Pass'),
('Olivia', 'Anderson', '2000-08-25', 'Physics', 50, 100, 'Fail'),
('Sophia', 'Thomas', '2001-01-30', 'English', 78, 100, 'Pass'),
('Ethan', 'Jackson', '2002-12-22', 'History', 64, 100, 'Pass');
➔ StudentResult.cs
using System;
using System.ComponentModel.DataAnnotations;
[Required]
[StringLength(100)]
public string FirstName { get; set; }
[Required]
[StringLength(100)]
public string LastName { get; set; }
[Required]
public DateTime DateOfBirth { get; set; }
50
[Required]
[StringLength(100)]
public string Subject { get; set; }
[Required]
public int MarksObtained { get; set; }
[Required]
public int TotalMarks { get; set; }
➔ HomeController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
➔ Index.cshtml
@model IEnumerable<StudentResult>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Student Results</title>
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bo
otstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h2 class="my-4">Student Results</h2>
<table class="table table-bordered">
<thead>
<tr>
<th>Student ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Date of Birth</th>
<th>Subject</th>
<th>Marks Obtained</th>
<th>Total Marks</th>
<th>Result</th>
</tr>
52
</thead>
<tbody>
@foreach (var result in Model)
{
<tr>
<td>@result.StudentId</td>
<td>@result.FirstName</td>
<td>@result.LastName</td>
<td>@result.DateOfBirth.ToString("yyyy-MM-
dd")</td>
<td>@result.Subject</td>
<td>@result.MarksObtained</td>
<td>@result.TotalMarks</td>
<td>@result.Result</td>
</tr>
}
</tbody>
</table>
</div>
</body>
</html>
➔ ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
➔ Employee.cs
using System;
using System.ComponentModel.DataAnnotations;
namespace YourProject.Models
{
public class Employee
{
[Key]
public int EmpId { get; set; }
[Required]
[StringLength(100)]
public string EmpName { get; set; }
[StringLength(200)]
public string Address { get; set; }
[StringLength(100)]
public string City { get; set; }
[Phone]
public string Contact { get; set; }
[StringLength(50)]
public string Qualification { get; set; }
54
public DateTime JoinDate { get; set; }
}
}
➔ ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
namespace YourProject.Data
{
public class ApplicationDbContext : DbContext
{
public
ApplicationDbContext(DbContextOptions<ApplicationDbContext>
options) : base(options)
{
}
➔ HomeController.cs
using Microsoft.AspNetCore.Mvc;
using YourProject.Data;
using YourProject.Models;
using System.Linq;
namespace YourProject.Controllers
{
public class HomeController : Controller
{
55
private readonly ApplicationDbContext _context;
[HttpPost]
public IActionResult Create(Employee employee)
{
if (ModelState.IsValid)
{
_context.Employees.Add(employee);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(employee);
}}}
56
➔ Index.cshtml
@model IEnumerable<YourProject.Models.Employee>
<!DOCTYPE html>
<html>
<head>
<title>Employee List</title>
</head>
<body>
<h1>Employee List</h1>
<a href="@Url.Action("Create", "Home")">Add New
Employee</a>
<table>
<thead>
<tr>
<th>Emp ID</th>
<th>Emp Name</th>
<th>Address</th>
<th>City</th>
<th>Contact</th>
<th>Qualification</th>
<th>Join Date</th>
</tr>
</thead>
<tbody>
@foreach (var emp in Model)
{
<tr>
<td>@emp.EmpId</td>
<td>@emp.EmpName</td>
<td>@emp.Address</td>
<td>@emp.City</td>
57
<td>@emp.Contact</td>
<td>@emp.Qualification</td>
<td>@emp.JoinDate.ToString("yyyy-MM-dd")</td>
</tr>
}
</tbody>
</table>
</body>
</html>
➔ Create.cshtml
@model YourProject.Models.Employee
<!DOCTYPE html>
<html>
<head>
<title>Create Employee</title>
</head>
<body>
<h1>Create Employee</h1>
<form method="post">
<div>
<label>Emp Name:</label>
<input type="text" name="EmpName" required />
</div>
<div>
<label>Address:</label>
<input type="text" name="Address" />
</div>
<div>
<label>City:</label>
<input type="text" name="City" />
58
</div>
<div>
<label>Contact:</label>
<input type="text" name="Contact" />
</div>
<div>
<label>Qualification:</label>
<input type="text" name="Qualification" />
</div>
<div>
<label>Join Date:</label>
<input type="date" name="JoinDate" required />
</div>
<div>
<button type="submit">Create Employee</button>
</div>
</form>
<a href="@Url.Action("Index", "Home")">Back to Employee
List</a>
</body>
</html>
➔ ApplicationDbContext.cs
public static void Seed(ApplicationDbContext context)
{
if (!context.Employees.Any())
{
context.Employees.AddRange(
new Employee { EmpName = "John Doe", Address = "123
Main St", City = "City A", Contact = "1234567890", Qualification =
"BSc", JoinDate = DateTime.Now },
59
new Employee { EmpName = "Jane Smith", Address = "456
Elm St", City = "City B", Contact = "2345678901", Qualification =
"MSc", JoinDate = DateTime.Now },
new Employee { EmpName = "Alice Brown", Address = "789
Oak St", City = "City C", Contact = "3456789012", Qualification =
"MBA", JoinDate = DateTime.Now },
new Employee { EmpName = "Bob Johnson", Address =
"101 Pine St", City = "City D", Contact = "4567890123",
Qualification = "PhD", JoinDate = DateTime.Now },
new Employee { EmpName = "Charlie Davis", Address =
"202 Birch St", City = "City E", Contact = "5678901234",
Qualification = "BEng", JoinDate = DateTime.Now },
new Employee { EmpName = "David Wilson", Address =
"303 Maple St", City = "City F", Contact = "6789012345",
Qualification = "BCom", JoinDate = DateTime.Now },
new Employee { EmpName = "Eva Martinez", Address =
"404 Cedar St", City = "City G", Contact = "7890123456",
Qualification = "BBA", JoinDate = DateTime.Now },
new Employee { EmpName = "Frank Lee", Address = "505
Willow St", City = "City H", Contact = "8901234567", Qualification
= "MSc", JoinDate = DateTime.Now },
new Employee { EmpName = "Grace Walker", Address =
"606 Fir St", City = "City I", Contact = "9012345678", Qualification
= "BSc", JoinDate = DateTime.Now },
new Employee { EmpName = "Hank Scott", Address = "707
Redwood St", City = "City J", Contact = "0123456789",
Qualification = "BA", JoinDate = DateTime.Now }
);
context.SaveChanges();
}
}
60
18. WAP to establish connection and test connection sql
command.
➔ HomeController.cs
using Microsoft.AspNetCore.Mvc;
using System.Data.SqlClient;
using System;
namespace YourProject.Controllers
{
public class HomeController : Controller
{
private readonly string connectionString =
"YourConnectionStringHere";
61
}
catch (Exception ex)
{
return $"Connection failed: {ex.Message}";
}
}
}
}
➔ Index.cshtml
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Database Connection Test</h1>
<p>@ViewBag.Message</p>
</div>
➔ HomeController.cs
using System.Collections.Generic;
62
using System.Web.Mvc;
using YourProject.Models;
// GET: Home
public ActionResult Index()
{
return View(records);
}
// POST: AddRecord
[HttpPost]
public ActionResult AddRecord(int recordId)
{
// Here, we're adding static records for simplicity.
var newRecord = new DataRecord
{
Id = recordId,
Name = "Name " + recordId,
Description = "Description for record " + recordId
};
records.Add(newRecord);
return RedirectToAction("Index");
}}
63
➔ Index.cshtml
@{
ViewBag.Title = "Home Page";
}
➔ AddRecord.cshtml
@model List<Record>
@{
ViewData["Title"] = "Add Records";
}
<h2>@ViewData["Title"]</h2>
65
{
<div>
<label for="record_@i">Record @i</label>
<input type="text" id="record_@i"
name="records[@i].Name" />
</div>
}
<button type="submit">Add Records</button>
</form>
➔ HomeController.cs
using Microsoft.AspNetCore.Mvc;
using YourNamespace.Models;
return View(records);
}
[HttpPost]
public IActionResult AddRecord(List<Record> records)
66
{
// Process the records (save them to a database, etc.)
if (ModelState.IsValid)
{
// Here, you could save the records to the database
return RedirectToAction("Index"); // Or a different page
}
return View(records);
}
}
➔ Model (AddItemModel.cs)
public class AddItemModel
{
public string ItemName { get; set; }
public decimal ItemPrice { get; set; }
}
➔ HomeController.cs
using Microsoft.AspNetCore.Mvc;
using YourProject.Models;
67
// GET: Home
public IActionResult Index()
{
return View(items);
}
➔ Index.cshtml
@model List<YourProject.Models.AddItemModel>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Add Item to Table</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/b
ootstrap.min.css">
68
</head>
<body>
<div class="container mt-5">
<h2>Add Item to Table</h2>
70