Question error object reference null after click submit button ?

ahmedaziz

Well-known member
Joined
Feb 22, 2023
Messages
55
Programming Experience
1-3
I working on MVC razor pages asp.net core 7 . I can't display success message after submit and insert data on same page .

I get error

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

error happen on Model.userModel.Branches

Expected Result is display success message after insert data success but after click submit button

data inserted and give me this error null reference exception

so How to solve this error ?

page model functions:
public class AddUserModel : PageModel

    {

        [BindProperty]

        public AddUserViewModel userModel { get; set; }

        [BindProperty]

        public UC.ADC.Core.Entities.SQL.User  User { get; set; }

        public string SuccessMessage { get; set; }

public AddUserModel(ADCContext db,OracleContext ora_db2)

        {

            

             _db = db;

            userModel = new AddUserViewModel();

        }

     public async Task<IActionResult> OnPost()

            {

                if (ModelState.IsValid)

                {

                    await _db.User.AddAsync(User);

                    await _db.SaveChangesAsync();

                    SuccessMessage = "Form submitted successfully!";

                    return Page();

                    

    

                }

                

            }

    public void OnGet()

            {

                userModel.Branches  = _db.Branch.ToList();

             }

  }

on adduser.cshtml

view of drop down list that give error:
@page "/AddUser"

<form method="post">

      



        <div class="form-group row">

            <label for="branch-select" class="col-sm-1 col-form-label" style="font-size:15px;font-family: 'Open Sans', sans-serif;font-weight: bold;">Branch</label>
<div class="col-sm-3">
<select id="branch-select" asp-for="User.iBranchCode" class="form-control" style=" margin-left:10px;font-size:15px;font-family: 'Open Sans' , sans-serif;font-weight: bold;">
<option value="">-- Select Branch --</option>
                
                     @foreach (var branch in Model.userModel.Branches)
                    {
<option value="@branch.iBranchCode">@branch.vBranchDesc</option>
                    }
</select>
</div>
</div>

<div class="form-group row" style="margin-left:200px;font-size:15px;font-family: 'Open Sans' , sans-serif;font-weight: bold;">

            <button type="submit" class="col-sm-1 btn btn-primary">Submit</button>
          
</div>

</form>
 
Use your debugger. Which variable or member does it show as being null?
 
Here is an example that has two submit buttons, first redirects back to the same page passing a string then in the Get sets a property which in turn on page load presents a popup while the second submit does nothing other than write to the console.

Full source

code behind:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
#pragma warning disable CS8618

namespace ShowMessageOnPost.Pages;
public class IndexModel : PageModel
{
    public string SuccessMessage { get; set; }

    public void OnGet(string sender)
    {
        if (sender is { })
        {
            SuccessMessage = "Finished";
        }
    }
    public Task<IActionResult> OnPostSubmit() =>
        Task.FromResult<IActionResult>(RedirectToPage("Index", new
        {
            sender = "Whatever"
        }));

    public PageResult OnPostSubmit1() => Page();
}

frontend code:
@page
@model IndexModel
@{
    ViewData["Title"] = "Dummy submit";
}

<link rel="stylesheet" href="~/lib/limonte-sweetalert2/sweetalert2.min.css" />
<script src="lib/limonte-sweetalert2/sweetalert2.all.min.js"></script>

<div class="container">
    
    <div class="alert alert-primary" role="alert">
        Example to display message on document load based on setting a property
    </div>

    <form method="post">

        <input type="hidden" asp-for="SuccessMessage" id="message"/>

        <input type="submit" 
               class="btn btn-primary" 
               value="Submit" 
               asp-page-handler="Submit"/>

        <input type="submit" 
               class="btn btn-primary" 
               value="Submit" asp-page-handler="Submit1"/>

    </form>

</div>

@section scripts{
    <script type="text/javascript">
        window.onload = function () {

            let msg = $('#message').val();

            if (msg.length > 0) {

                const popupConfiguration = Swal.mixin({
                    customClass: { confirmButton: 'btn btn-primary' },
                    buttonsStyling: false
                });

                popupConfiguration.fire({
                    icon: '',
                    text: msg,
                    allowOutsideClick: false,
                    width: '200px',
                    height: '300px'
                });
            } else {
                console.log('Nada');
            }
        };
    </script>

}

The popup is from Sweetalert2
 

Latest posts

Back
Top Bottom