I have been working through the official Microsoft tutorial intended to teach the use of C# ASP.NET Core MVC (https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud). I have experience with OOP languages like C++ and Java, but I'm new to both C# and this specific framework.
The tutorial itself is working great; I have a web app that can perform basic CRUD operations on students. For my purposes, all that's important to know is that a student has a LastName
, FirstName
and a unique, automatically generated ID
which functions as its primary key in the database.
I'd like to add a check to ensure that the combination of the student's last and first name is unique. I would also like to be able to sanitize the input by removing leading spaces, etc. I was able to do this with the creation of new data in the Create
method, but I'm lost as to how to add this to the recommended Edit
method in the controller (I've trimmed everything I know isn't vital from the below to save space):
[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditPost(int? id)
{
var studentToUpdate = await _context.Students.SingleOrDefaultAsync(s => s.ID == id);
if (await TryUpdateModelAsync<Student>(
studentToUpdate,
"",
s => s.FirstMidName, s => s.LastName))
{
try
{
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
return View(studentToUpdate);
}
QUESTION: how can I check and manipulate the user's data before it is put in the database?
From what I've been able to dig up, TryUpdateModelAsync
function is somehow getting the information the user submits and using it to update the model. However, the documentation hasn't given me any clue how I could intervene and become an active part of that process. I'd like to check/manipulate the data myself before allowing the update, but I'm not sure how to access it. Is it in an object? Is there a function that can let me run operations on it? After a full day of Googling, I have yet to find it. I'm sure it must be possible, because putting unsanitized data fresh from the user into a database doesn't seem like a good practice. (at least that's what I heard from Bobby Tables)
An example of input in the view, in case it helps:
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
I hope I've provided enough information; if there's any important context I'm leaving out, please let me know.