Bazı durumlarda kayıt güncellememiz gerekebilir. Örneğin, bir veri yanlış girilmiştir ve onu düzeltmemiz lazım. Bir önceki yazıyı okuduysanız ilk iki kaydın verileri boş, ancak biz ilgili alanları güncelleyerek o boşlukları giderebiliriz.
İlk olarak KelimeController'da bir Guncelle adında iki tane action metot yazalım:
[HttpGet]
public async Task<IActionResult> Guncelle(int? id)
{
if (id == null)
return NotFound();
return View(await _context.Kelimes.FirstOrDefaultAsync(o => o.Id == id));
}
[HttpPost]
public async Task<IActionResult> Guncelle(Kelime kelime)
{
if(kelime == null)
return NotFound();
Kelime? kayitliKelime = _context.Kelimes.FirstOrDefault(o => o.Id == kelime.Id);
if (kayitliKelime != null)
{
kayitliKelime.SKelime = kelime.SKelime;
kayitliKelime.SAnlam = kelime.SAnlam;
await _context.SaveChangesAsync();
return RedirectToAction("Listele");
}
return NotFound();
}
}
}
Get metotu olarak çalışacak Guncelle için bir tane view ekleyelim(Guncelle.cshtml). Ekle.cshtml dosyasındaki kodun aynısını bazı değişiklikler yaparak kullanıyorum:
@model OgrenKelime.Models.Kelime
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
ViewData["Title"] = "Kelime Güncelle";
Layout = "~/Views/_Layout.cshtml";
}
@{
<h1>@ViewData["Title"]</h1>
<form method="post" action="Guncelle">
<div class="row">
<input hidden asp-for="Id" />
<div class="col">
<input type="text" class="form-control" placeholder="Kelimeyi yaz.." asp-for="SKelime">
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Kelimenin anlamı.." asp-for="SAnlam">
</div>
<div class="col">
<button type="submit" class="btn btn-primary">Güncelle</button>
</div>
</div>
</form>
}
Kayıtları listelerken aynı zamanda o satırların içerisine buton koyabiliriz(Listele.cshtml):
@model IEnumerable<OgrenKelime.Models.Kelime>
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
ViewData["Title"] = "Kelime Listesi";
Layout = "~/Views/_Layout.cshtml";
}
@{
<h1>@ViewData["Title"]</h1>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Kelime</th>
<th scope="col">Anlamı</th>
<th scope="col">Kayıt Tarihi</th>
<th scope="col">İşlemler</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.SKelime</td>
<td>@item.SAnlam</td>
<td>@item.DtKayitTarihi</td>
<td>
<a asp-action="Guncelle" asp-route-id="@item.Id">Güncelle</a>
</td>
</tr>
}
</tbody>
</table>
}
Testimizi yapalım:
İşlem başarılı.
Hiç yorum yok:
Yorum Gönder