I have simple login page like this:
Login.cshtml
@page
@model GDPR.Views.Account.LoginModel
@{
}
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<html>
<body>
<p>Login </p>
<form method="post">
<div asp-validation-summary="All"></div>
Username: <input asp-for="loginData.Username" value="username" /><br />
Password: <input asp-for="loginData.Password" value="password" /><br />
<br />
<input type="submit" value="Login" />
@Html.AntiForgeryToken()
</form>
</body>
</html>
and code behind:
public class LoginModel : PageModel
{
[BindProperty] // Bind on Post
public LoginData loginData { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (ModelState.IsValid)
{
.......
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return RedirectToPage("/Home/Index");
}
else
{
ModelState.AddModelError("", "username or password is blank");
return Page();
}
}
public class LoginData
{
[Required]
public string Username { get; set; }
[Required, DataType(DataType.Password)]
public string Password { get; set; }
}
}
When I run the app I get an error: ArgumentNullException value cannot be null, param name : viewData.
What could be the reason for that error?
Your @page on the first line is null which is what's causing the error. Either remove the @page statement or use it to define the page to be displayed.
It may be null because the namespace of the view model hasn't been added to _viewImports.
Add the namespace to _viewImports so that the application can use the model behind the razor page.
Hope this helps.
Here's some information on Razor pages:
https://docs.microsoft.com/en-us/aspnet/core/mvc/razor-pages/?view=aspnetcore-2.1&tabs=visual-studio
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With