Search code examples
c#asp.net-corerazor-pages

ASP.NET Razor page model binding not working


I have the following form on a razor page:

<form method="post">
    <table>
        <tr>
            <td style="padding-bottom: 10px;" class="login-entry">User Name</td>
            <td style="padding-bottom: 10px;"><input type="text" asp-for="LoginName" class="logins" autocomplete="off" /></td>
        </tr>
        <tr>
            <td style="padding-bottom: 10px;" class="login-entry">Password</td>
            <td style="padding-bottom: 10px;"><input type="password" asp-for="Password" class="logins" /></td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:right;"><input type="submit" value="login" /></td>
        </tr>
    </table>
</form>

Then, within my PageModel, I have two properties, and OnPostAsync:

public string LoginName { get; set; }

 public string Password { get; set; }

 public async Task<IActionResult> OnPostAsync()
{
    // Login code here
}

The problem is when I debug the page, enter a user name and password, and click login, inside the OnPostAsync method the properties LoginName and Password are both null.

Does anyone have any ideas on why this isn't working? Or a way of tracking down these sorts of things when they don't work?


Solution

  • You can add this attribute [BindProperty], like this:

        [BindProperty]
        public string LoginName { get; set; }
        [BindProperty]
        public string Password { get; set; }
    
        public async Task<IActionResult> OnPostAsync()
        {
            // Login code here
        }
    

    Result: enter image description here