.Net Core Proje Model Güncelleme

Gökay Umutlu
2 min readApr 19, 2023

--

Aşağıda görüldüğü üzere Proje isimli başlık ve resim içeren bir model yapısı var.

[Key]
public int Proje_Id { get; set; }
public string? Baslik { get; set; }
public string? Resim_Url { get; set; }
[NotMapped]
public IFormFile? Resim { get; set; }

Kullanıcı mevcut olan bir projeyi güncellemek istediği zaman aşağıdaki gibi bir ekran verileri kullanıcıdan almamızı sağlıyor.

<form asp-controller="Proje" asp-action="ProjeGuncelle" enctype="multipart/form-data" method="post">
@Html.HiddenFor(x=>x.Proje_Id)
<div class="card-body ">
<div class="form-group">
<label for="projeGuncellemeAciklama">Proje Başlığı</label>
@Html.TextBoxFor(x=>x.Baslik,new {@class="form-control"})
@Html.ValidationMessageFor(x=>x.Aciklama,"",new { @class = "text-danger" })
</div>
<div class="form-group">
<label asp-for="Resim">Resim Linki</label>
<div class="custom-file">
<input asp-for="Resim" class="custom-file-input" id="customFile" accept=".png, .jpg, .jpeg" />
<label class="custom-file-label" for="customFile">Resim Seç</label>
<small class="w-100">@Html.DisplayFor(x=>x.Resim_Url,new {@class="form-control"}) seçildi.</small>
</div>
</div>
</div>
<div class="card-footer">
<a href="/Proje/Index/" class="btn btn-primary">Geri Dön</a>
<button type="submit" class="btn btn-success">Kaydet</button>
</div>
</form>

Güncelleme işlemini gerçekleştiren Controller kod bölümü ise şöyle:

[HttpGet]
public IActionResult ProjeGuncelle(int id)
{
var values = projeManager.GetT(id);
return View(values);
}
[HttpPost]
public IActionResult ProjeGuncelle(Proje updatedProje)
{
var values = projeManager.GetT(updatedProje.Proje_Id);
validationResult = validations.Validate(updatedProje);
if (validationResult.IsValid)
{
if (ModelState.IsValid)
{
if (updatedProje.Resim != null)
{
string uniqueName = UploadFile(updatedProje);
updatedProje.Resim_Url = "/Path-To-Folder/" + uniqueName;
System.IO.File.Delete(webHostEnvironment.WebRootPath + values.Resim_Url);
}
else
{
updatedProje.Resim_Url = values.Resim_Url;
}
}
projeManager.Update(updatedProje);;
return RedirectToAction("Index");
}
else
{
foreach (var item in validationResult.Errors)
{
ModelState.AddModelError(item.PropertyName, item.ErrorMessage);
}
}
return View();
}

--

--