Commit 6d5d7206 authored by TTrueBenji's avatar TTrueBenji

Реализовать удаление.

***
- пофиксили ошибку миграций: пришлось удалить миграции и создать заново. (на удаленный репозиторий не был добавлей файл дизайнер миграций.)
- Реализовали удаление смартфона из БД с подтверждением.
- Добавили страницу ошибок.
- Удалили форму с главной страницы.
***
parent 320b1ea3
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using PhoneStore.ViewModels;
namespace PhoneStore.Controllers
{
public class ErrorsController : Controller
{
private readonly Dictionary<int, ErrorViewModel> _errorResolver;
public ErrorsController()
{
_errorResolver = new Dictionary<int, ErrorViewModel>();
_errorResolver.Add(404, new ErrorViewModel
{
StatusCode = 404,
Message = "Ресурс не найден",
Title = "Oops... Страница не найдена"
});
_errorResolver.Add(400, new ErrorViewModel
{
StatusCode = 400,
Message = "Сервер не смог обработать запрос",
Title = "Oops... Ошибка"
});
_errorResolver.Add(500, new ErrorViewModel
{
StatusCode = 500,
Message = "Сервер не смог обработать запрос",
Title = "Oops... Ошибка"
});
_errorResolver.Add(777, new ErrorViewModel
{
StatusCode = 777,
Message = "Сущность не найдена",
Title = "Oops... Ошибка"
});
}
[Route("Error/{statusCode}")]
[ActionName("Error")]
public IActionResult HttpStatusCodeHandler(int statusCode)
{
if (_errorResolver.ContainsKey(statusCode))
{
return View(_errorResolver[statusCode]);
}
return View(_errorResolver[404]);
}
}
}
\ No newline at end of file
......@@ -86,15 +86,10 @@ namespace PhoneStore.Controllers
{
return "tets";
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier});
}
}
}
\ No newline at end of file
......@@ -29,7 +29,7 @@ namespace PhoneStore.Controllers
{
var phone = _db.Phones.FirstOrDefault(p => p.Id == phoneId);
if (phone is null)
return Content("Такого телефона нет.");
return RedirectToAction("Error", "Errors", new {statusCode = 777});
Order order = new Order
{
Phone = phone
......
......@@ -6,11 +6,11 @@ using PhoneStore.Models;
namespace PhoneStore.Controllers
{
public class PhoneController : Controller
public class PhonesController : Controller
{
private readonly MobileContext _db;
public PhoneController(MobileContext db)
public PhonesController(MobileContext db)
{
_db = db;
}
......@@ -39,5 +39,28 @@ namespace PhoneStore.Controllers
_db.SaveChanges();
return RedirectToAction("Index");
}
[HttpGet]
public IActionResult Delete(int phoneId)
{
var phone = _db.Phones.FirstOrDefault(p => p.Id == phoneId);
if (phone is null)
return BadRequest();
return View(phone);
}
[HttpPost]
[ActionName("Delete")]
public IActionResult Confirm(int phoneId)
{
var phone = _db.Phones.FirstOrDefault(p => p.Id == phoneId);
if (phone is null)
return BadRequest();
_db.Phones.Remove(phone);
_db.SaveChanges();
return RedirectToAction("Index");
}
}
}
\ No newline at end of file
using Microsoft.EntityFrameworkCore.Migrations;
namespace PhoneStore.Migrations
{
public partial class AddBasketEntity : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Baskets",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
PhoneId = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Baskets", x => x.Id);
table.ForeignKey(
name: "FK_Baskets_Phones_PhoneId",
column: x => x.PhoneId,
principalTable: "Phones",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Baskets_PhoneId",
table: "Baskets",
column: "PhoneId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Baskets");
}
}
}
......@@ -8,8 +8,8 @@ using PhoneStore.Models;
namespace PhoneStore.Migrations
{
[DbContext(typeof(MobileContext))]
[Migration("20220616111154_AddBasketEntity")]
partial class AddBasketEntity
[Migration("20220622133702_Init")]
partial class Init
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
......
......@@ -2,7 +2,7 @@
namespace PhoneStore.Migrations
{
public partial class Initial : Migration
public partial class Init : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
......@@ -21,6 +21,25 @@ namespace PhoneStore.Migrations
table.PrimaryKey("PK_Phones", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Baskets",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
PhoneId = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Baskets", x => x.Id);
table.ForeignKey(
name: "FK_Baskets_Phones_PhoneId",
column: x => x.PhoneId,
principalTable: "Phones",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
......@@ -43,6 +62,11 @@ namespace PhoneStore.Migrations
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Baskets_PhoneId",
table: "Baskets",
column: "PhoneId");
migrationBuilder.CreateIndex(
name: "IX_Orders_PhoneId",
table: "Orders",
......@@ -51,6 +75,9 @@ namespace PhoneStore.Migrations
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Baskets");
migrationBuilder.DropTable(
name: "Orders");
......
using System;
namespace PhoneStore.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
\ No newline at end of file
......@@ -17,7 +17,7 @@
</ItemGroup>
<ItemGroup>
<Folder Include="Pages" />
<Folder Include="Migrations" />
</ItemGroup>
</Project>
......@@ -56,6 +56,7 @@ namespace PhoneStore
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseStatusCodePagesWithRedirects("/Error/{0}");
}
else
{
......
namespace PhoneStore.ViewModels
{
public class ErrorViewModel
{
public int StatusCode { get; set; }
public string Title { get; set; }
public string Message { get; set; }
}
}
\ No newline at end of file
This diff is collapsed.
......@@ -5,10 +5,4 @@
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
<form asp-action="Test">
<input type="text" name="id" placeholder="id">
<input type="text" name="quantity" placeholder="quantity">
<button type="submit">Отправить</button>
</form>
\ No newline at end of file
</div>
\ No newline at end of file
......@@ -8,7 +8,7 @@
<h2>Заполните форму для добавления устройства</h2>
<div class="row">
<div class="phone_add_form col-md-6">
<form asp-action="Create" asp-controller="Phone" method="post">
<form asp-action="Create" asp-controller="Phones" method="post">
<div class="form_row">
<label for="name">
Наименование
......
@model Phone
@{
ViewBag.Title = "title";
Layout = "_Layout";
}
<div class="card text-center">
<div class="card-header">
Ахтунг!
</div>
<div class="card-body">
<h5 class="card-title">Вы уверены?</h5>
<p class="card-text">Данные могут быть безвозвратно удалены.</p>
<form asp-action="Delete" asp-controller="Phones" method="post">
<input type="text" name="phoneId" value="@Model.Id" hidden>
<a class="btn btn-outline-warning" asp-action="Index">Отмена</a>
<button class="btn btn-danger">Удалить</button>
</form>
</div>
</div>
\ No newline at end of file
......@@ -5,7 +5,7 @@
Layout = "_Layout";
}
<a asp-action="Create" asp-controller="Phone">Добавить устройство</a>
<a asp-action="Create" asp-controller="Phones">Добавить устройство</a>
@* https://localhost:5001/Phone/Create method GET*@
@if (Model.Count == 0)
{
......@@ -46,6 +46,14 @@ else
Заказать
</a>
</td>
<td>
<a asp-route-phoneId="@phone.Id"
asp-action="Delete"
asp-controller="Phones"
class="btn btn-danger">
Удалить
</a>
</td>
</tr>
}
</table>
......
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
\ No newline at end of file
......@@ -25,7 +25,7 @@
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Phone" asp-action="Index">Смартфоны</a>
<a class="nav-link text-dark" asp-area="" asp-controller="Phones" asp-action="Index">Смартфоны</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Orders" asp-action="Index">Заказы</a>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment