0

I'm very new to ASP.NET and I'm trying some things out right now. I try to make a simple dashboard right now which displays some set numbers, but I get this System.NullReferenceException The whole day I try to fix this, but it keeps throwing this exception.

index.cshtml:

@model XSP.ViewModels.DashboardViewModel

              <img src="assets/images/plane-icon.png" alt="deliver-icon">
                                    </span>
                                    <h2>Errors</h2>
                                </div><!--/.icon-box-->
                                <h3>@Model.errors</h3>
                                <p>0 This Week</p>
                            </div><!--/.profile-state-->
                        </div><!--/.col-->

My HomeController where the values are getting filled:

    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            DashboardViewModel dashboard = new DashboardViewModel();

            dashboard.onlineplayers = 1;
            dashboard.errors = 222;
            return View(dashboard);
        }
    }

And here's my ViewModel

    public  class DashboardViewModel
    {
        public  int onlineplayers { get; set; };
        public  int errors { get; set; };
    }

I already checked the other threads before I asked this question where the solution was always in the Controller adding return View(XX); but I have a return value.

Thanks for your help :)

Matt U
  • 4,970
  • 9
  • 28
Hakuryuu
  • 25
  • 1
  • 6
  • When debugging your code, what line throws the exception ? – Jawad May 22 '21 at 18:43
  • I alredy saw that post and no it did not help me (maybe I'm just too stupid). This line throws the exception: `

    @Model.errors

    `
    – Hakuryuu May 22 '21 at 18:52
  • Try debugging `Index` method and see whether the `dashboard` object is being passed correctly. I think that the page you're rendering is not actually `Index` page, but some other. That's why you're getting `nullreference` – Miraziz May 22 '21 at 19:47
  • You mean in the HomeController? If yes, no it does not get passed. – Hakuryuu May 22 '21 at 19:55

1 Answers1

0

try this, I think it resolves your issue.

you should ignore ; in your class.

 public  class DashboardViewModel
    {
        public  int onlineplayers { get; set; }
        public  int errors { get; set; }
    }

Update

The solution is just remove the @page keyword.For example a Index.cshtml razor page will get it's model from Index.cshtml.cs file method.

Pritom Sarkar
  • 2,154
  • 3
  • 11
  • 26