@model Contact
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="editModalLabel">Изменить контакт</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="editForm" asp-action="Edit" onsubmit="return validateForm()">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label">Имя</label>
<input asp-for="Name"id="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PhoneNumber" class="control-label">Номер</label>
<input asp-for="PhoneNumber" id="PhoneNumber" class="form-control" />
<span asp-validation-for="PhoneNumber" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="JobTitle" class="control-label">Должность</label>
<input asp-for="JobTitle" id="JobTitle" class="form-control" />
<span asp-validation-for="JobTitle" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="BirthDay" class="control-label">Дата рождения</label>
<input asp-for="BirthDay" id="BirthDay" class="form-control" />
<span asp-validation-for="BirthDay" class="text-danger"></span>
</div>
<div class="form-group">
<br />
<input type="submit" value="Сохранить" class="btn btn-success" />
</div>
</form>
</div>
</div>
</div>
</div>
<script src="/js/Edit.js"></script>
@model WebApplication3.Models.Contact
@{
ViewData["Title"] = "Details";
}
@await Html.PartialAsync("Edit", new Contact(@Model.Name,@Model.PhoneNumber,@Model.JobTitle,@Model.BirthDay))
<h1>Информация</h1>
<div>
<h4>Контакт</h4>
<hr />
<dl class="row">
<dt class = "col-sm-2">
@Html.DisplayName("Имя")
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Name)
</dd>
<dt class = "col-sm-2">
@Html.DisplayName("Номер")
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.PhoneNumber)
</dd>
<dt class = "col-sm-2">
@Html.DisplayName("Должность")
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.JobTitle)
</dd>
<dt class = "col-sm-2">
@Html.DisplayName("Дата Рождения")
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.BirthDay)
</dd>
</dl>
</div>
<div>
<a asp-action="Edit" asp-route-id="@Model.PhoneNumber" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#editModal" > Изменить контакт </a> |
<a asp-action="Index" class="btn btn-info">Назад к списку</a>
</div>
public class HomeController : Controller
{
private readonly WebApplication3Context _context;
public HomeController(WebApplication3Context context)
{
_context = context;
}
//GET: Contacts
public async Task<IActionResult> Index()
{
return View(await _context.Contact.ToListAsync());
}
// GET: Contacts/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null || _context.Contact == null)
{
return NotFound();
}
var contact = await _context.Contact
.FirstOrDefaultAsync(m => m.PhoneNumber == id);
if (contact == null)
{
return NotFound();
}
return View(contact);
}
// GET: Contacts/Create
public IActionResult Create()
{
return PartialView("Create");
}
//POST: Contacts/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Name,PhoneNumber,JobTitle,BirthDay")] Contact contact)
{
if (ModelState.IsValid)
{
_context.Add(contact);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return PartialView("Create", contact);
}
// GET: Contacts/Edit/
public async Task<IActionResult> Edit23123(string id)
{
if (id == null || _context.Contact == null)
{
return NotFound();
}
var contact = await _context.Contact.FindAsync(id);
if (contact == null)
{
return NotFound();
}
return PartialView("Edit",contact);
}
// POST: Contacts/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(string id, [Bind("Name,PhoneNumber,JobTitle,BirthDay")] Contact contact)
{
if (id != contact.PhoneNumber)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(contact);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ContactExists(contact.PhoneNumber))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(contact);
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool ContactExists(string id)
{
return _context.Contact.Any(e => e.PhoneNumber == id);
}
}
<code lang="javascript">
function validateForm(e) {//валидация полей
const errors = document.getElementsByClassName('validation-error');
while (errors.length > 0) {
errors[0].parentNode.removeChild(errors[0]);
}
let valid = true;
const name = document.getElementById("Name");
if (!name.value) { // если не заполнено
name.style.border = "2px solid red";
document.querySelector('label[for="Name"]').innerHTML +=
'<span class="validation-error"> <font color="red"> Укажите имя </font></span>';
valid = false;
}
else
name.style.border = "1px solid #ced4da"
const PhoneNumber = document.getElementById("PhoneNumber");
if (!PhoneNumber.value) { // если не заполнено
PhoneNumber.style.border = "2px solid red";
document.querySelector('label[for="PhoneNumber"]').innerHTML +=
'<span class="validation-error"> <font color="red"> Укажите номер </font></span>';
valid = false;
}
else { // если заполнено, то проверяем на корректность номера регулярным выражением
const re = /^^[1-9]+[0-9]*$/;
if (!re.test(PhoneNumber.value)) {
PhoneNumber.style.border = "2px solid red";
document.querySelector('label[for="PhoneNumber"]').innerHTML +=
'<span class="validation-error"> <font color="red"> Некорректный номер. Используйте только цифры. </font></span>';
valid = false;
}
else {
PhoneNumber.style.border = "1px solid #ced4da"
}
}
const jobTitle = document.getElementById("JobTitle");
if (!jobTitle.value) { // если не заполнено
jobTitle.style.border = "2px solid red";
document.querySelector('label[for="JobTitle"]').innerHTML += ' <span class="validation-error"> <font color="red"> Укажите должность </font></span>';
valid = false;
}
else {
jobTitle.style.border = "1px solid #ced4da"
}
if (valid == false) {
e.preventDefault(); // предотвращаем отправку формы, если есть ошибки валидации
}
return valid;
}
const form = document.getElementById("editForm");
form.addEventListener('submit', validateForm);
}
</code>
</spoiler>