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

How to avoid nullreference error when trying to add data to viewmodel?

$
0
0

Trying to learn programming with Razor pages in asp.net core 2. The page should provide an registration form for events. The database lookup based on the event id in the querystring works, however I want to save some of the data in the viewmodel, and thought it might go like this:

public class EventRegistrationModel : PageModel
{
    private readonly losol.EventManagement.Data.ApplicationDbContext _context;

    public EventRegistrationModel(
        ApplicationDbContext context
        )
    {
        _context = context;
    }

    [BindProperty]
    public RegisterVM RegistrationVM { get; set; }

    public class RegisterVM
    {
        public int EventInfoId {get;set;}
        public string EventInfoTitle {get;set;}
        public string EventInfoDescription {get;set;}
        public string UserId {get;set;}

        public string Name { get; set; }
        public string Email { get; set; }

    }

    public async Task<IActionResult> OnGetAsync(int? id)
    {
        if (id == null)
        {
            return RedirectToPage("./Index");
        }

        var eventinfo = await _context.EventInfos.FirstOrDefaultAsync(m => m.EventInfoId == id);
        if (eventinfo == null)
        {
            return NotFound();
        }
        else
        {
           RegistrationVM.EventInfoId = eventinfo.EventInfoId;
           RegistrationVM.EventInfoTitle = eventinfo.Title;
           RegistrationVM.EventInfoDescription = eventinfo.Description;
        }
        return Page();
    }

However I do get an "NullReferenceException: Object reference not set to an instance of an object." when running this. How could I save the data from database to the viewmodel?

Errormessage:

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

losol.EventManagement.Pages.Register.EventRegistrationModel+<OnGetAsync>d__12.MoveNext() in Event.cshtml.cs, line 90


Viewing all articles
Browse latest Browse all 9386

Trending Articles



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