0
0

Base figure adding

This commit is contained in:
Sergey Chebotar 2023-03-02 07:28:22 +03:00
parent 6cb87f6c78
commit 607d029030
7 changed files with 210 additions and 161 deletions

View File

@ -1,109 +1,132 @@
using System.Data; using System.Data;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using MyDarling.Models; using MyDarling.Models;
namespace MyDarling.Controllers namespace MyDarling.Controllers
{ {
public class BundleController : Controller public class BundleController : Controller
{ {
private DataContext context; private DataContext context;
private IWebHostEnvironment environment;
public BundleController(DataContext context) public BundleController(DataContext context, IWebHostEnvironment environment)
{ {
this.context = context; this.environment = environment;
} this.context = context;
}
public ActionResult Index() public ActionResult Index()
{ {
return View(context.UnderwearBundles.Include(b => b.Figures)); return View(context.UnderwearBundles.Include(b => b.Figures));
} }
public ActionResult Create() public ActionResult Create()
{ {
return View(); return View();
} }
[HttpPost] [HttpPost]
public async Task<ActionResult> Create([Bind] UnderwearBundle bundle) public async Task<ActionResult> Create([Bind] UnderwearBundle bundle)
{ {
try try
{ {
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
await context.UnderwearBundles.AddAsync(bundle); await context.UnderwearBundles.AddAsync(bundle);
context.SaveChanges(); context.SaveChanges();
return RedirectToAction(nameof(Index)); return RedirectToAction(nameof(Index));
} }
} }
catch (DataException) catch (DataException)
{ {
ModelState.AddModelError("", "Unable to save changes"); ModelState.AddModelError("", "Unable to save changes");
} }
return View(bundle); return View(bundle);
} }
public async Task<ActionResult> Details(int id) public async Task<ActionResult> Details(int id)
{ {
return View(await context.UnderwearBundles.Include(b => b.Figures).Where(b => b.Id == id).FirstOrDefaultAsync()); return View(await context.UnderwearBundles.Include(b => b.Figures).Where(b => b.Id == id).FirstOrDefaultAsync());
} }
public async Task<ActionResult> Edit(int id)
{
return View(nameof(Details), await context.UnderwearBundles.FindAsync(id));
}
[HttpPost] public async Task<ActionResult> Edit(int id)
public async Task<ActionResult> Edit(int? id) {
{ return View(nameof(Details), await context.UnderwearBundles.FindAsync(id));
if (id == null) }
{
return NotFound();
}
var bundle = await context.UnderwearBundles.FindAsync(id);
if (bundle == null)
{
return NotFound();
}
if (await TryUpdateModelAsync<UnderwearBundle>(
bundle,
"",
b => b.Name, b => b.Description, b => b.Figures, b => b.Price))
{
try
{
await context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
catch (System.Exception)
{
ModelState.AddModelError("", "Unable to save changes");
}
}
return View(bundle);
}
[HttpPost] [HttpPost]
public async Task<ActionResult> Delete(int id) public async Task<ActionResult> Edit(int? id)
{ {
var bundleToDelete = await context.UnderwearBundles.FindAsync(id);
if (bundleToDelete == null) if (id == null)
{ {
return NotFound(); return NotFound();
} }
try var bundle = await context.UnderwearBundles.FindAsync(id);
{ if (bundle == null)
context.UnderwearBundles.Remove(bundleToDelete); {
await context.SaveChangesAsync(); return NotFound();
return RedirectToAction(nameof(Index)); }
}
catch(DbUpdateException) var file = Request.Form.Files.FirstOrDefault();
{
return RedirectToAction(nameof(Delete), new {id = id, saveChangesError = true}); if (await TryUpdateModelAsync<UnderwearBundle>(
} bundle,
} "",
} b => b.Name, b => b.Description, b => b.Figures, b => b.Price))
{
if (file != null)
{
var newFigure = new Figure();
bundle.Figures.Add(newFigure);
newFigure.FilePath = $"/Content/{bundle.Id}/{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
var savePath = environment.WebRootPath + "/Content/" + bundle.Id + "/";
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
using var fileStream = new FileStream(environment.WebRootPath + newFigure.FilePath, FileMode.Create);
await file.CopyToAsync(fileStream);
}
try
{
await context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
catch (System.Exception)
{
ModelState.AddModelError("", "Unable to save changes");
}
}
return View(bundle);
}
[HttpPost]
public async Task<ActionResult> Delete(int id)
{
var bundleToDelete = await context.UnderwearBundles.FindAsync(id);
if (bundleToDelete == null)
{
return NotFound();
}
try
{
context.UnderwearBundles.Remove(bundleToDelete);
await context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
catch (DbUpdateException)
{
return RedirectToAction(nameof(Delete), new { id = id, saveChangesError = true });
}
}
}
} }

View File

@ -54,5 +54,26 @@ namespace MyDarling.Controllers
} }
return View(figure); return View(figure);
} }
[HttpPost]
public async Task<ActionResult> Delete(int id)
{
var figureToDelete = await context.Figures.FindAsync(id);
if (figureToDelete == null)
{
return NotFound();
}
try
{
context.Figures.Remove(figureToDelete);
await context.SaveChangesAsync();
return RedirectToAction(nameof(Index), "Bundle");
}
catch (DbUpdateException)
{
return RedirectToAction(nameof(Delete), new { id = id, saveChangesError = true });
}
}
} }
} }

View File

@ -1,64 +1,64 @@
using Microsoft.EntityFrameworkCore; // using Microsoft.EntityFrameworkCore;
namespace MyDarling.Models // namespace MyDarling.Models
{ // {
public static class SeedData // public static class SeedData
{ // {
public static void SeedDatabase(DataContext context) // public static void SeedDatabase(DataContext context)
{ // {
context.Database.Migrate(); // context.Database.Migrate();
if (context.UnderwearBundles.Count() == 0) // if (context.UnderwearBundles.Count() == 0)
{ // {
var aliceFigures = new List<Figure> // var aliceFigures = new List<Figure>
{ // {
new Figure() // new Figure()
{ // {
Description = @"Комплект из бежевого эластичного кружева с голубой отделкой.", // Description = @"Комплект из бежевого эластичного кружева с голубой отделкой.",
FilePath = "/content/0/img/IMG_4896.JPG" // FilePath = "/content/0/img/IMG_4896.JPG"
}, // },
new Figure() // new Figure()
{ // {
Description = @"В комплект входит бра, 2 трусиков (на высокой посадке и стандартной на регуляции) и чокер. Низ можно сделать на выбор стринги/бразильянки.", // Description = @"В комплект входит бра, 2 трусиков (на высокой посадке и стандартной на регуляции) и чокер. Низ можно сделать на выбор стринги/бразильянки.",
FilePath = "/content/0/img/IMG_4902.JPG" // FilePath = "/content/0/img/IMG_4902.JPG"
} // }
}; // };
var nikkiFigures = new List<Figure> // var nikkiFigures = new List<Figure>
{ // {
new Figure() // new Figure()
{ // {
Description = @"Базовый сет из мягкой эластичной сетки.", // Description = @"Базовый сет из мягкой эластичной сетки.",
FilePath = "/content/1/img/IMG_4897.JPG" // FilePath = "/content/1/img/IMG_4897.JPG"
}, // },
new Figure() // new Figure()
{ // {
Description = @"В комплект входит лиф на косточках и 2 трусиков бразильянки на высокой посадке и стринги на стандартной посадке с регуляцией. Доступен в цветах: желтый, черный, бежевый молочный.", // Description = @"В комплект входит лиф на косточках и 2 трусиков бразильянки на высокой посадке и стринги на стандартной посадке с регуляцией. Доступен в цветах: желтый, черный, бежевый молочный.",
FilePath = "/content/1/img/IMG_4898.JPG" // FilePath = "/content/1/img/IMG_4898.JPG"
} // }
}; // };
context.Figures.AddRange(aliceFigures); // context.Figures.AddRange(aliceFigures);
context.Figures.AddRange(nikkiFigures); // context.Figures.AddRange(nikkiFigures);
context.SaveChanges(); // context.SaveChanges();
var alice = new UnderwearBundle // var alice = new UnderwearBundle
{ // {
Name = "Alice", // Name = "Alice",
Figures = aliceFigures, // Figures = aliceFigures,
Description = @"Комплект из бежевого эластичного кружева с голубой отделкой.", // Description = @"Комплект из бежевого эластичного кружева с голубой отделкой.",
Price = 3000 // Price = 3000
}; // };
var nikki = new UnderwearBundle // var nikki = new UnderwearBundle
{ // {
Name = "Nikki", // Name = "Nikki",
Figures = nikkiFigures, // Figures = nikkiFigures,
Description = @"Базовый сет из мягкой эластичной сетки.", // Description = @"Базовый сет из мягкой эластичной сетки.",
Price = 3800 // Price = 3800
}; // };
context.UnderwearBundles.AddRange(alice, nikki); // context.UnderwearBundles.AddRange(alice, nikki);
context.SaveChanges(); // context.SaveChanges();
} // }
} // }
} // }
} // }

View File

@ -17,7 +17,7 @@ app.UseStaticFiles();
app.MapControllers(); app.MapControllers();
app.MapDefaultControllerRoute(); app.MapDefaultControllerRoute();
var context = app.Services.CreateScope().ServiceProvider.GetRequiredService<DataContext>(); // var context = app.Services.CreateScope().ServiceProvider.GetRequiredService<DataContext>();
SeedData.SeedDatabase(context); // SeedData.SeedDatabase(context);
app.Run(); app.Run();

View File

@ -11,7 +11,7 @@
<body> <body>
<container> <container>
<form asp-action="Edit" asp-route-id="@Model.Id" method="post" class="m-2"> <form asp-action="Edit" asp-route-id="@Model.Id" method="post" enctype="multipart/form-data" class="m-2">
<div asp-validation-summary="All"></div> <div asp-validation-summary="All"></div>
<div class="form-group"> <div class="form-group">
<label asp-for="Name" class="form-label">Name:</label> <label asp-for="Name" class="form-label">Name:</label>
@ -33,9 +33,12 @@
</a> </a>
</div> </div>
</div> </div>
} }
</div> </div>
</div> </div>
<div class="form-group">
<input type="file" name="file" />
</div>
<div class="form-group"> <div class="form-group">
<label asp-for="Price" class="form-label">Price:</label> <label asp-for="Price" class="form-label">Price:</label>
<input asp-for="Price" class="form-control" /> <input asp-for="Price" class="form-control" />

View File

@ -26,6 +26,7 @@
@Html.TextAreaFor(model => model.Description, new { @class="form-control", @rows = 2 }) @Html.TextAreaFor(model => model.Description, new { @class="form-control", @rows = 2 })
</div> </div>
<button type="submit" class="btn btn-primary mt-3">Save</button> <button type="submit" class="btn btn-primary mt-3">Save</button>
<button asp-action="Delete" asp-route-id="@Model.Id" method="post" class="btn btn-primary mt-3">Delete</button>
</form> </form>
</body> </body>

View File

@ -4,13 +4,14 @@
<section class="projects-section bg-light" id="projects"> <section class="projects-section bg-light" id="projects">
<div class="container px-3 px-lg-4 mt-4"> <div class="container px-3 px-lg-4 mt-4">
<div class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center"> <div class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center">
@foreach (var bundle in @Model.Where(b => b.Price != 0)) @foreach (var bundle in @Model.Where(b => b.Price != 0 && b.Figures.Count > 0)
.OrderByDescending(b => b.Id))
{ {
<div class="col mb-5"> <div class="col mb-5">
<div class="card h-100"> <div class="card h-100">
<a data-src="@bundle.Figures.FirstOrDefault()?.FilePath" data-fancybox="@bundle.Id" <a data-src="@bundle.Figures[0].FilePath" data-fancybox="@bundle.Id"
data-caption="@bundle.Figures.FirstOrDefault()?.Description"><img class="card-img-top" data-caption="@bundle.Figures[0].Description"><img class="card-img-top"
src="@bundle.Figures.FirstOrDefault()?.FilePath" alt="@bundle.Name" /></a> src="@bundle.Figures[0].FilePath" alt="@bundle.Name" /></a>
@for (int i = 1; i < @bundle.Figures.Count(); i++) @for (int i = 1; i < @bundle.Figures.Count(); i++)
{ {
<a data-src="@bundle.Figures[i].FilePath" data-fancybox="@bundle.Id" <a data-src="@bundle.Figures[i].FilePath" data-fancybox="@bundle.Id"