14. CRUD Operations
CRUD stands for Create, Read, Update, Delete: the four basic operations on stored data. In MVC each one is usually an action, and the data-changing ones use POST. Following the pattern below gives a complete data screen for any model.
Key points
- Read: Index (list) and Details (one item).
- Create: GET shows the form, POST saves.
- Update: GET Edit loads the item, POST Edit saves changes.
- Delete: GET asks for confirmation, POST removes the item.
Example: Create, edit and delete actions
[HttpPost]
public async Task<IActionResult> Create(Student s)
{
if (!ModelState.IsValid) return View(s);
_db.Students.Add(s);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
[HttpPost]
public async Task<IActionResult> Edit(int id, Student s)
{
if (id != s.Id) return BadRequest();
if (!ModelState.IsValid) return View(s);
_db.Update(s);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
[HttpPost]
public async Task<IActionResult> Delete(int id)
{
var s = await _db.Students.FindAsync(id);
if (s == null) return NotFound();
_db.Students.Remove(s);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
Show explanation
Each action checks the data, changes the database, saves, and redirects so a page refresh does not submit the form again (the Post-Redirect-Get pattern).