Mvc: TryUpdateModelAsync problems with Razor Pages

Created on 11 Oct 2017  路  4Comments  路  Source: aspnet/Mvc

Code to reproduce the bug at https://github.com/Rick-Anderson/TryUpdateModelAsync

To reproduce the bug:

  • Run the project and tap on Students (http://localhost:xxx/Students)
  • Tap Create and submit. The scaffolded code works.
  • Tap Create TryUpdateModelAsync and submit. That code doesn't work.

Code bug here

Most helpful comment

I made the following two one line changes and everything lit up.

--- a/ContosoUniversity/ContosoUniversity/Pages/Students/Create2.cshtml.cs
+++ b/ContosoUniversity/ContosoUniversity/Pages/Students/Create2.cshtml.cs
@@ -42,11 +42,12 @@ namespace ContosoUniversity.Pages.Students

             if (await TryUpdateModelAsync<Student>(
                 emptyStudent,
-                "",
+                "student",
                 s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate))
             {
                 try
                 {
+                    _context.Students.Add(emptyStudent);
                     await _context.SaveChangesAsync();
                     return RedirectToPage("./Index");

All 4 comments

The problem is passing in an empty prefix. The prefix used here should be "Student" or "student" to match the <input/>s in the form.

@dougbu changed to Student - no joy

This is exactly the same code used in a MVC controller, and no prefix was used there.

I made the following two one line changes and everything lit up.

--- a/ContosoUniversity/ContosoUniversity/Pages/Students/Create2.cshtml.cs
+++ b/ContosoUniversity/ContosoUniversity/Pages/Students/Create2.cshtml.cs
@@ -42,11 +42,12 @@ namespace ContosoUniversity.Pages.Students

             if (await TryUpdateModelAsync<Student>(
                 emptyStudent,
-                "",
+                "student",
                 s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate))
             {
                 try
                 {
+                    _context.Students.Add(emptyStudent);
                     await _context.SaveChangesAsync();
                     return RedirectToPage("./Index");

Yeah, Razor Pages tutorial has slightly different code (contains prefix)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mdmoura picture mdmoura  路  33Comments

pranavkm picture pranavkm  路  57Comments

MicahZoltu picture MicahZoltu  路  37Comments

NTaylorMullen picture NTaylorMullen  路  66Comments

johnnyoshika picture johnnyoshika  路  57Comments