Error while validation fields in MVC ASP.NET Core

Advertisements

I have this form, where user sees his account’s amount and can send money to other user just by providing email. The problem is, when user provides wrong data, function returns page, but I get NullExceptionError.

Actually, I think, that validators work fine, but there is something wrong with return type, or with how this function returns page.

Here is Index.cshtml.cs:

 public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly WebBankDbContext _context;
        private readonly UserManager<IdentityUser> userManager;
        private readonly SignInManager<IdentityUser> signInManager;

        public IdentityUser user;
        public Account account;

        [BindProperty]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }
        [BindProperty]
        [RegularExpression("([1-9][0-9]*)")]
        public int AmountToSend { get; set; }

        public IndexModel(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager, ILogger<IndexModel> logger, WebBankDbContext context)
        {
            _logger = logger;
            _context = context;
            this.userManager = userManager;
            this.signInManager = signInManager;
        }

        public IActionResult OnPost(string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                var destinationAccount = (from st in _context.Users where st.Email == Email select st.Id).First();
                Console.WriteLine(destinationAccount);
                if (destinationAccount != null)
                {
                    if (returnUrl == null || returnUrl == "/")
                    {
                        return RedirectToPage("Index");
                    }
                    else
                    {
                        return RedirectToPage(returnUrl);
                    }
                }
            }
            return Page();
        }

        public async Task OnGetAsync()
        {
            if (signInManager.IsSignedIn(User))
            {
                user = await userManager.GetUserAsync(User);
                account = (from st in _context.Accounts where st.UserId == user.Id select st).First();
            }
        }
    }

Here is Index.cshtml. This is how it form looks like. When I provide wrong data, it show this NullExceptionError in h5.

<h5>Your balance: @(Model.account.Amount)$</h5>

    <div class="text-center">
        <p>Send money just by providing user ID</p>
    </div>

    <form method="post">
        <div class="mb-3">
            <label class="col-form-label" asp-for="Email">Receiver email:</label>
            <input type="text" class="form-control" asp-for="Email" />
            <span asp-validation-for="Email" class="text-danger"></span>
        </div>
        <div class="mb-3">
            <label class="col-form-label" asp-for="AmountToSend">Amount:</label>
            <input type="text" class="form-control" asp-for="AmountToSend" />
            <span asp-validation-for="AmountToSend" class="text-danger"></span>
        </div>
        <div class="mb-3">
            <button type="submit" class="btn btn-primary">Send money</button>
        </div>
    </form>

>Solution :

When you POST you lose the state of your Model.
You want to fill your Model when you POST.

What I mean with that, is that you GET the page, it works fine.
Then you POST some data, the POST code will run, but now it’s in a new instance of PageModel. This means that Model.account is null.

You can do one of two things:

  1. Fill the data before you do return Page()
  2. Redirect to the GET action instead of returning Page().

Good luck!

Leave a ReplyCancel reply