Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArgumentNullException : Value cannot be null. Parameter name : viewData

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.

enter image description here

What could be the reason for that error?

like image 898
Neno Avatar asked Apr 19 '18 09:04

Neno


2 Answers

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.

like image 159
Snos Avatar answered Sep 30 '22 17:09

Snos


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

like image 31
Rbulmer55 Avatar answered Sep 30 '22 18:09

Rbulmer55