Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Nullreferenceexception when using ViewModel

$
0
0

Hi all,

I've decided to use ASP.NET core and razor pages for a little mini-project at work. It's been a while since i did any dev work. One thing that has me stumped at the moment is trying to get a ViewModel to work with a razor page. When i use the default page model, it works. However when i switch to the ViewModel i get a null reference exception on the first select control defined in the HTML.

Exception received:

NullReferenceException: Object reference not set to an instance of an object

SharedData.Pages.AccountCoding.Index_Page+<<ExecuteAsync>b__16_0>d.MoveNext() in Index.cshtml

<div class="source">
  1. <select asp-for="SelectedEntityCode" asp-items="Model.Entities" onchange="this.form.submit();">
</div>

Below is the Razor Page Index.cshtml:

@page
@model SharedData.ViewModels.AccountCodingView<!-- snipped for brevity --><form asp-page-handler="entity" method="post"><div class="form-group"><label asp-for="SelectedEntityCode" class="control-label"></label><select asp-for="SelectedEntityCode" asp-items="Model.Entities" onchange="this.form.submit();"><option value="">select an entity</option></select><!-- snipped for brevity -->

The null reference exception occors on the <select line in the above snippet. This breakpoint is hitbefore anything else. The OnGet codebehind isn't even hit in the Index.cshtml.cs file shown below:

public class IndexModel : PageModel
{
    private readonly SharedData.Models.SharedDataContext _context;
    AccountCodingView accountCodingView;

    public IndexModel(SharedData.Models.SharedDataContext context)
    {
        _context = context;
	accountCodingView = new AccountCodingView();
    }
    
    public IActionResult OnGet(string entityCode)
    {
	LoadEntities(entityCode);
	return Page();
    }


// snipped

There must be something easy i'm missing here. In the sample RazorPagesMovie solution on the asp.net website, the constructor in the Inex.cshtml.cs is hit first. In mine, nothing is hit at all.

Cheers,

Sam


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>