Neno
Neno

Reputation: 767

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?

Upvotes: 16

Views: 15642

Answers (6)

Kshitij Jhangra
Kshitij Jhangra

Reputation: 607

Based on your code description, I can say that you are using .Net Core MVC and you are trying to execute your login page.

The @page directive is correct with no problem. Seems you have not configure your Startup.cs properly. Try the code below:

For ASP .Net Core 3.1

public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
    }

and in Configure:

app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });

and it will look like:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }

For ASP .Net Core 2.2

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Includes support for Razor Pages and controllers.
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseMvc();
    }
}

Execute your code, there should be no error.

Upvotes: 0

manit
manit

Reputation: 694

While removing @page from your file throws no erorrs, if you render a PageModel from a Controller, the PageModel does not get initialized correctly. Your Get and Post functions will also not fire.

Create a separate folder for your PageModels

/Pages ..../Login.cshtml ..../Logoin.cshtml.cs

Upvotes: 0

redar ismail
redar ismail

Reputation: 171

look at the top of the page and delete the directive @Page, @page expects a request it turns the page to act like MVC. Here is a good tutorial to follow. https://learn.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-2.2&tabs=visual-studio

Upvotes: 0

Snos
Snos

Reputation: 296

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.

Upvotes: 28

Rbulmer55
Rbulmer55

Reputation: 41

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://learn.microsoft.com/en-us/aspnet/core/mvc/razor-pages/?view=aspnetcore-2.1&tabs=visual-studio

Upvotes: 2

Vietvo
Vietvo

Reputation: 101

Try to change : asp-for="loginData.Username" to asp-for="Model.loginData.Username"

Upvotes: -1

Related Questions