Enrolment no.
202203103510495
Practical No. 6
AIM -Develop ASP.NET Core MVC project with following functionalities:
• Create “Employee”, “Manager”, and “Clerk” model classes.
• Use “Global using” and demonstrate use of nullable type.
CODE
EmployeeContoller.cs using
Microsoft.AspNetCore.Mvc; using
EmployeeManagement.Models; using
System.Collections.Generic;
namespace EmployeeManagement.Controllers
{ public class EmployeesController : Controller
{ public IActionResult Index()
{
// Sample data for demonstration purposes
var employees = new List<Employee>
{
new Employee { Id = 1, Name = "John Doe", Position = "Manager" },
new Employee { Id = 2, Name = "Jane Smith", Position = "Clerk" }
};
// Pass the list of employees to the view
return View(employees);
}
}
}
ManagerController.cs using
Microsoft.AspNetCore.Mvc; using
EmployeeManagement.Models; using
System.Collections.Generic; namespace
Enrolment no. 202203103510495
EmployeeManagement.Controllers { public
class ManagersController : Controller
{ public IActionResult Index()
{
// Sample data for demonstration
var managers = new
List<Manager>
{
new Manager { Id = 1, Name = "Alice Johnson", Position = "Manager",
NumberOfTeams = 3 }, new Manager { Id = 2, Name = "Bob Brown", Position
= "Manager", NumberOfTeams = 5 }
};
return View(managers);
}
}
}
clerkContoller.cs using
Microsoft.AspNetCore.Mvc; using
EmployeeManagement.Models; using
System.Collections.Generic;
namespace EmployeeManagement.Controllers
{ public class ClerksController : Controller
{ public IActionResult Index()
{
// Sample data for demonstration
var clerks = new List<Clerk>
{
new Clerk { Id = 1, Name = "Charlie Smith", Position = "Clerk", Department =
"Finance" }, new Clerk { Id = 2, Name = "Dana White", Position = "Clerk",
Department = "HR" }
};
return View(clerks);
}
}
}
Enrolment no. 202203103510495
Models/Employee.cs namespace
EmployeeManagement.Models
{ public class Employee
{ public int Id { get; set; } public string? Name { get; set; } // Nullable
string type for Name public string? Position { get; set; } // Nullable
string type for Position
}
}
Models/Manager.cs namespace
EmployeeManagement.Models
{
public class Manager : Employee
{
public int? NumberOfTeams { get; set; } // Nullable int type for NumberOfTeams
}
}
Models/clerk.cs namespace
EmployeeManagement.Models
{
public class Clerk : Employee
{ public string? Department { get; set; } // Nullable string type for Department
}
}
Views/clerk/Index.cshtml
@model IEnumerable<EmployeeManagement.Models.Clerk>
<h2>Clerks List</h2>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Department</th>
</tr>
</thead>
<tbody>
Enrolment no. 202203103510495
@foreach (var clerk in Model)
{
<tr>
<td>@clerk.Id</td>
<td>@clerk.Name</td>
<td>@clerk.Position</td>
<td>@clerk.Department</td>
</tr>
}
</tbody>
</table>
Views/Manager/Index.cshtml
@model IEnumerable<EmployeeManagement.Models.Manager>
<h2>Managers List</h2>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Number of Teams</th>
</tr>
</thead>
<tbody>
@foreach (var manager in Model)
{
<tr>
<td>@manager.Id</td>
<td>@manager.Name</td>
<td>@manager.Position</td>
<td>@manager.NumberOfTeams</td>
</tr>
}
</tbody>
</table>
Views/Employee/Index.cshtml
@model IEnumerable<EmployeeManagement.Models.Employee>
Enrolment no. 202203103510495
<h2>Employees List</h2>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
</tr>
</thead>
<tbody>
@foreach (var employee in Model)
{
<tr>
<td>@employee.Id</td>
<td>@employee.Name</td>
<td>@employee.Position</td>
</tr>
}
</tbody>
</table>
Data/Applicationdbcontext.cs
using Microsoft.EntityFrameworkCore;
using EmployeeManagement.Models;
namespace EmployeeManagement.Data
{ public class ApplicationDbContext : DbContext
{ public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) :
base(options)
{
}
public DbSet<Employee> Employees { get; set; }
public DbSet<Manager> Managers { get; set; } public
DbSet<Clerk> Clerks { get; set; }
}
}
Enrolment no. 202203103510495
OUTPUT
Enrolment no. 202203103510495
Enrolment no. 202203103510495
Practical No. 8
AIM - Develop ASP.NET Core MVC application to download information from
Web URL. Create asynchronous method and use it to implement the
functionality.
CODE Program.cs
using WebDownloader.Services; var builder =
WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddHttpClient<IWebDownloadService, WebDownloadService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{ app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default", pattern:
"{controller=Home}/{action=Index}/{id?}");
app.Run();
Enrolment no. 202203103510495
Services/WebDownloadService.cs
using System.Net.Http; using
System.Threading.Tasks;
namespace WebDownloader.Services
{ public interface IWebDownloadService
{
Task<string> DownloadContentAsync(string url);
}
public class WebDownloadService : IWebDownloadService
{ private readonly HttpClient _httpClient;
public WebDownloadService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> DownloadContentAsync(string url)
{ var response = await _httpClient.GetStringAsync(url);
return response;
}
}
}
Views/Home/Index.cshtml
@{
ViewData["Title"] = "Home Page";
}
<h1>Download Content</h1>
<form method="get" action="">
<label for="url">Enter URL:</label>
<input type="text" id="url" name="url" />
<button type="submit">Download</button>
</form>
Enrolment no. 202203103510495
@if (ViewBag.Content != null)
{
<h2>Content from URL:</h2>
<pre>@ViewBag.Content</pre>
}
OUTPUT
Enrolment no. 202203103510495
Practical No. 9
AIM - Develop ASP.NET Core MVC application to demonstrate use of Cookie,
Session, Query String, and Hidden Field.
CODE
HomeController.cs using
Microsoft.AspNetCore.Mvc; using
Microsoft.AspNetCore.Http; using
System;
namespace CookieSessionDemo.Controllers
{ public class HomeController : Controller
{ public IActionResult Index()
{
// Set a cookie
Response.Cookies.Append("UserName", "JohnDoe", new CookieOptions { Expires
= DateTimeOffset.UtcNow.AddDays(1) });
// Set session value
HttpContext.Session.SetString("SessionKey", "SessionValue");
return View();
}
public IActionResult About()
{
// Read cookie
ViewBag.UserName = Request.Cookies["UserName"];
// Read session value
ViewBag.SessionValue = HttpContext.Session.GetString("SessionKey");
return View();
}
public IActionResult QueryStringDemo(string name)
Enrolment no. 202203103510495
{
ViewBag.Name = name;
return View();
}
[HttpPost] public IActionResult HiddenFieldDemo(string
hiddenFieldValue)
{
ViewBag.HiddenFieldValue = hiddenFieldValue;
return View();
}
}
}
Program.cs var builder =
WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddSession(options =>
{ options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{ app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization(); app.UseSession();
// Add this line to use session
app.MapControllerRoute(
Enrolment no. 202203103510495
name: "default", pattern:
"{controller=Home}/{action=Index}/{id?}");
app.Run();
Views/Home/Index.cshtml
@{
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">building Web apps
with ASP.NET Core</a>.</p>
</div>
@* Index.cshtml *@
<h1>Index Page</h1>
<p>Welcome to the Cookie and Session demo!</p>
<a href="/Home/About">Go to About Page</a>
<br />
<a href="/Home/QueryStringDemo?name=JohnDoe">Pass Query String</a>
<br />
<form method="post" action="/Home/HiddenFieldDemo">
<input type="hidden" name="hiddenFieldValue" value="HiddenValue" />
<button type="submit">Submit Hidden Field</button>
</form>
View/Home/About.cshtml
@* About.cshtml *@
<h1>About Page</h1>
<p>Cookie Value: @ViewBag.UserName</p>
<p>Session Value: @ViewBag.SessionValue</p>
<a href="/">Back to Index</a>
View/Home/QueryStringDemo.cshtml
@* QueryStringDemo.cshtml *@
<h1>Query String Demo Page</h1>
<p>Query String Name: @ViewBag.Name</p>
Enrolment no. 202203103510495
<a href="/">Back to Index</a>
View/Home/HiddenFieldDemo.cshtml
@* HiddenFieldDemo.cshtml *@
<h1>Hidden Field Demo Page</h1>
<p>Hidden Field Value: @ViewBag.HiddenFieldValue</p>
<a href="/">Back to Index</a>
OUTPUT
Enrolment no. 202203103510495
Enrolment no. 202203103510495
Practical No. 10
AIM - Develop ASP.NET Core MVC application to demonstrate use of
Response Caching and Caching Data using IMemoryCache.
CODE
HomeController.cs using Microsoft.AspNetCore.Mvc; using
Microsoft.Extensions.Caching.Memory; // Import necessary namespace
namespace CachingDemoApp.Controllers // Ensure the correct namespace is
used
{ public class HomeController : Controller
{
private readonly IMemoryCache _memoryCache;
// Inject IMemoryCache through the constructor public
HomeController(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
// Apply Response Caching
[ResponseCache(Duration = 60)]
public IActionResult Index()
{
ViewBag.Timestamp = DateTime.Now;
// Implement Data Caching using IMemoryCache
if (!_memoryCache.TryGetValue("CachedTime", out string
cachedTime))
{
// Cache the current time if not already cached
cachedTime = DateTime.Now.ToString("T");
Enrolment no. 202203103510495
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromSeconds(30)) // Reset the
expiration time if accessed within 30 seconds
.SetAbsoluteExpiration(TimeSpan.FromMinutes(1)); // Max cache
time is 1 minute
_memoryCache.Set("CachedTime", cachedTime,
cacheEntryOptions);
}
ViewBag.CachedTime = cachedTime;
return View();
}
}
}
Program.cs
using Microsoft.Extensions.Caching.Memory; var
builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddResponseCaching(); // Add response caching
builder.Services.AddMemoryCache(); // Add in-memory caching
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{ app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
Enrolment no. 202203103510495
app.UseHttpsRedirection(); app.UseStaticFiles();
app.UseRouting(); app.UseAuthorization();
app.UseResponseCaching(); // Enable response caching
app.MapControllerRoute(
name: "default", pattern:
"{controller=Home}/{action=Index}/{id?}");
app.Run();
Views/Home/Index.html
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Current Time: @ViewBag.Timestamp</p>
<p>Cached Time: @ViewBag.CachedTime</p>
</div>
OUTPUT