What happens in TryUpdateModelAsync

So, I am doing this microsoftware tutorial on the ASP.NET core with EF 6, and it just went through updating the model using the editing controller.

There is this part of the code that really confused me that what I represent (and perhaps hopefully) is not so confusing for you.

var studentToUpdate = await _context.Students.SingleOrDefaultAsync(s => s.ID == id); if (await TryUpdateModelAsync<Student>( studentToUpdate, "", s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate)) // goes on to save the context 

So, the only thing this controller accepts as a parameter is its int id and how it holds studentToUpdate . What I donโ€™t quite understand here, where does it get update values โ€‹โ€‹from?

What i know:

  • TryUpdateModelAsync<Student>
    • first argument: model to update
    • second argument: the prefix (?) from the link: the prefix used when searching for values โ€‹โ€‹in.
    • Third argument: the linq operator, which I suspect is related to the solution I'm looking for.
  • Cancel the debugger before studentToUpdate.FirstMidNames was Carson (original), but after function execution it was Carsey (new). The Carsey line Carsey always in this> Request> Form> Results View (which contained a list of all the values โ€‹โ€‹from the form).

So, I understand that the TryUpdateModelAsync function somehow uses the linq expression and the result form to get new values โ€‹โ€‹for studentToUpdate , but I really don't see how and where this is done?

+7
c # asp.net-core-mvc
source share
1 answer

Without going into too many technical details. Call TryUpdateModelAsync in the above example

 if (await TryUpdateModelAsync<Student>( studentToUpdate, "", s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate)){ //... } 

Updates the specified instance of Student studentToUpdate using values โ€‹โ€‹from the current current ControllerContext that would be populated with the data provided in the request. It uses lambda expressions (expressions) that represent the top-level properties that must be enabled for the current model when trying to update. It will only accept the values โ€‹โ€‹of these properties and update the model.

So, in the above example, even if the entire model was provided by the form, it will only update the FirstMidName , LastName and EnrollmentDate tags in the specified instance.

+3
source share

All Articles