Dotnet 11 -15_merged
Dotnet 11 -15_merged
Practical: 11
Aim: Develop ASP.NET Core MVC application with following functionalities:
• Create model classes “Product”, “Category”, “Supplier”
• Use code first approach with entity framework
• Store and retrieve data to/from MySQL database.
Code:
HomeController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using practical11.Data;
using System.Threading.Tasks;
namespace practical11.Controllers
{
public class HomeController : Controller
{
private readonly ApplicationDbContext _context;
Data/ ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
using practical11.Models;
namespace practical11.Data
{
public class ApplicationDbContext : DbContext
{
Web Technology with .NET Enrollment No: 202203103510495
public ApplicationDbContext(DbContextOptions<ApplicationDbContext>
options) : base(options)
{
}
Data/ DbInitializer.cs
using practical11.Models;
using System.Linq;
namespace practical11.Data
{
public static class DbInitializer
{
public static void Initialize(ApplicationDbContext context)
{
context.Database.EnsureCreated();
new Supplier{Name="Supplier2",
ContactInfo="supplier2@example.com"},
new Supplier{Name="Supplier3",
ContactInfo="supplier3@example.com"}
};
foreach (Supplier s in suppliers)
{
context.Suppliers.Add(s);
}
context.SaveChanges();
Models/ Category.cs
namespace practical11.Models
{
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Product> Products { get; set; }
}
}
Models/ Product.cs
namespace practical11.Models
{
Web Technology with .NET Enrollment No: 202203103510495
// Foreign Key
public int CategoryId { get; set; }
public Category Category { get; set; }
// Foreign Key
public int SupplierId { get; set; }
public Supplier Supplier { get; set; }
}
}
Models/ Supplier.cs
namespace practical11.Models
{
public class Supplier
{
public int Id { get; set; }
public string Name { get; set; }
public string ContactInfo { get; set; }
public ICollection<Product> Products { get; set; }
}
}
Index.cshtml
@model IEnumerable<practical11.Models.Product>
@{
ViewData["Title"] = "Home Page";
}
<h2>Product List</h2>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Category</th>
<th>Supplier</th>
Web Technology with .NET Enrollment No: 202203103510495
</tr>
</thead>
<tbody>
@foreach (var product in Model)
{
<tr>
<td>@product.Name</td>
<td>@product.Price.ToString("C")</td>
<td>@product.Category.Name</td>
<td>@product.Supplier.Name</td>
</tr>
}
</tbody>
</table>
Output
Web Technology with .NET Enrollment No: 202203103510495
Web Technology with .NET Enrollment No: 202203103510495
Practical: 12
Aim: Develop ASP.NET Core Web API which retrieves data from MySQL
database. Also create APIs to create, delete, and update objects..
Code:
HomeController.cs
using Microsoft.AspNetCore.Mvc;
using MyMvcApp.Models;
using System.Diagnostics;
namespace MyMvcApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyMvcApp.Data;
using MyMvcApp.Models;
using System.Linq;
using System.Threading.Tasks;
namespace MyMvcApp.Controllers
Web Technology with .NET Enrollment No: 202203103510495
{
public class ProductsController : Controller
{
private readonly DataContext _context;
// GET: Products
public async Task<IActionResult> Index()
{
return View(await _context.Products.ToListAsync());
}
// GET: Products/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
return View(product);
}
// GET: Products/Create
public IActionResult Create()
{
return View();
}
// POST: Products/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Price")]
Product product)
{
if (ModelState.IsValid)
{
Web Technology with .NET Enrollment No: 202203103510495
_context.Add(product);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(product);
}
// GET: Products/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
// POST: Products/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Price")]
Product product)
{
if (id != product.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(product);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(product.Id))
{
return NotFound();
}
else
Web Technology with .NET Enrollment No: 202203103510495
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(product);
}
// GET: Products/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
return View(product);
}
// POST: Products/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var product = await _context.Products.FindAsync(id);
_context.Products.Remove(product);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
DataContext.cs
using Microsoft.EntityFrameworkCore;
using MyMvcApp.Models;
Web Technology with .NET Enrollment No: 202203103510495
namespace MyMvcApp.Data
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) :
base(options) { }
Product.cs
namespace MyMvcApp.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection":
"server=localhost;database=mydatabase;user=root;password=8530"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Output
Web Technology with .NET Enrollment No: 202203103510495
Web Technology with .NET Enrollment No: 202203103510495
Practical: 13
Aim: Develop ASP.NET Core MVC application to demonstrate use of
ViewData, ViewBag and TempData.
Code:
HomeController.cs
using Microsoft.AspNetCore.Mvc;
namespace practical13.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
// Using ViewData
ViewData["Message"] = "This message is from ViewData.";
// Using ViewBag
ViewBag.Message = "This message is from ViewBag.";
// Using TempData
TempData["Message"] = "This message is from TempData.";
return View();
}
Index.cshtml
@{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
Web Technology with .NET Enrollment No: 202203103510495
Output
Web Technology with .NET Enrollment No: 202203103510495
Practical: 14
Aim: Develop ASP.NET Core MVC application to demonstrate model
validation with implicit validation and explicit validation.
Code:
HomeController.cs
using Microsoft.AspNetCore.Mvc;
using practical14.Models;
using System.Collections.Generic;
namespace practical14.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(Person person)
{
// Implicit validation
if (ModelState.IsValid)
{
// Explicit validation
if (person.IsValid(out List<string> validationErrors))
{
ViewBag.Message = "Person is valid.";
}
else
{
foreach (var error in validationErrors)
{
ModelState.AddModelError(string.Empty, error);
}
}
}
return View(person);
}
}
}
Model/Person.cs
Web Technology with .NET Enrollment No: 202203103510495
using System.ComponentModel.DataAnnotations;
namespace practical14.Models
{
public class Person
{
[Required(ErrorMessage = "Name is required")]
[StringLength(100, ErrorMessage = "Name can't be longer than 100
characters")]
public string Name { get; set; }
Index.cshtml
@model practical14.Models.Person
@{
ViewData["Title"] = "Person Form";
}
<h2>Person Form</h2>
Web Technology with .NET Enrollment No: 202203103510495
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
Output
Web Technology with .NET Enrollment No: 202203103510495
Web Technology with .NET Enrollment No: 202203103510495
Practical: 15
Aim: Develop ASP.NET Core MVC Forms application to provide Create, Read,
Update and Delete functionality.
Code:
HomeController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using practical15.Data;
using practical15.Models;
using System.Threading.Tasks;
namespace practical15.Controllers
{
public class HomeController : Controller
{
private readonly ApplicationDbContext _context;
// GET: Home
public async Task<IActionResult> Index()
{
return View(await _context.Items.ToListAsync());
}
// GET: Home/Create
public IActionResult Create()
{
return View();
}
// POST: Home/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Name,Quantity")] Item
item)
{
if (ModelState.IsValid)
{
_context.Add(item);
Web Technology with .NET Enrollment No: 202203103510495
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(item);
}
// GET: Home/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
// POST: Home/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id,
[Bind("Id,Name,Quantity")] Item item)
{
if (id != item.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(item);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ItemExists(item.Id))
{
return NotFound();
}
else
{
Web Technology with .NET Enrollment No: 202203103510495
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(item);
}
// GET: Home/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
return View(item);
}
// POST: Home/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var item = await _context.Items.FindAsync(id);
_context.Items.Remove(item);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ItemsController.cs
using Microsoft.AspNetCore.Mvc;
Web Technology with .NET Enrollment No: 202203103510495
using Microsoft.EntityFrameworkCore;
using practical15.Data;
using practical15.Models;
using System.Threading.Tasks;
namespace practical15.Controllers
{
public class ItemsController : Controller
{
private readonly ApplicationDbContext _context;
// GET: Items
public async Task<IActionResult> Index()
{
return View(await _context.Items.ToListAsync());
}
// GET: Items/Create
public IActionResult Create()
{
return View();
}
// POST: Items/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Quantity")]
Item item)
{
if (ModelState.IsValid)
{
_context.Add(item);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(item);
}
// GET: Items/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
Web Technology with .NET Enrollment No: 202203103510495
return NotFound();
}
// POST: Items/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id,
[Bind("Id,Name,Quantity")] Item item)
{
if (id != item.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(item);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ItemExists(item.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(item);
}
// GET: Items/Delete/5
public async Task<IActionResult> Delete(int? id)
{
Web Technology with .NET Enrollment No: 202203103510495
if (id == null)
{
return NotFound();
}
return View(item);
}
// POST: Items/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var item = await _context.Items.FindAsync(id);
_context.Items.Remove(item);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
Model/Item.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace practical15.Models
{
public class Item
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
Web Technology with .NET Enrollment No: 202203103510495
[Required]
[Range(1, 1000)]
public int Quantity { get; set; }
}
}
ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
using practical15.Models;
namespace practical15.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext>
options)
: base(options)
{
}
Create.cshtml
@model practical15.Models.Item
@{
ViewData["Title"] = "Create Item";
}
<h2>Create Item</h2>
<h4>Item</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
Web Technology with .NET Enrollment No: 202203103510495
<div class="form-group">
<label asp-for="Quantity" class="control-label"></label>
<input asp-for="Quantity" class="form-control" />
<span asp-validation-for="Quantity" class="text-
danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
Delete.cshtml
@model practical15.Models.Item
@{
ViewData["Title"] = "Delete Item";
}
<h2>Delete Item</h2>
<form asp-action="Delete">
<input type="hidden" asp-for="Id" />
Web Technology with .NET Enrollment No: 202203103510495
Edit.cshtml
@model practical15.Models.Item
@{
ViewData["Title"] = "Edit Item";
}
<h2>Edit Item</h2>
<h4>Item</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Quantity" class="control-label"></label>
<input asp-for="Quantity" class="form-control" />
<span asp-validation-for="Quantity" class="text-
danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
Index.cshtml
@model IEnumerable<practical15.Models.Item>
@{
ViewData["Title"] = "Items List";
Web Technology with .NET Enrollment No: 202203103510495
<h2>Items List</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Quantity)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
<a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Output
Web Technology with .NET Enrollment No: 202203103510495
Web Technology with .NET Enrollment No: 202203103510495
Asha M. Tarsadia Institute of Computer Science and Technology
Network Security (CY5009)
INDEX
Date of Submission:
Institute Stamp