Hello. I am facing an issue with null exception after calling OnPost method in my razor pages site.
When i call method OnGet i load all of the information about property. public void OnGet(int? id)
{
Property = pS.GetProperty(id);
DownPayment = Property.Price * 0.2m;
MaximumLoan = Property.Price - DownPayment;
}
But when i call method OnPost
public IActionResult OnPostCalculateMortgage(int? id)
{
if (!ModelState.IsValid)
{
return Page();
}
// Determine which strategy to use based on the amount to be borrowed
ICalculateStrategy strategy;
if (AmountToBorrow > MaximumLoan * 0.5m)
{
strategy = new FixedRateStrategy();
}
else
{
strategy = new FloatingRateStrategy();
}
// Set the strategy and calculate the monthly payments
Property.Calculator.SetStrategy(strategy);
try
{
// Calculate the monthly payments
List<string> paymentSchedule = Property.Calculator.CalculateMonthlyPayment(AmountToBorrow, LoanTerm);
// Add the payment schedule to ViewData to display in the page
ViewData["PaymentSchedule"] = paymentSchedule;
}
catch (InvalidOperationException ex)
{
// Handle exceptions and add error messages to ModelState
ModelState.AddModelError(string.Empty, "An error occurred while calculating the mortgage.");
}
catch (NegativeLoanTermException ex)
{
ModelState.AddModelError(string.Empty, "Loan term must be positive and at least 12 months.");
}
catch (NegativePrincipalException ex)
{
ModelState.AddModelError(string.Empty, "The amount to borrow must be greater than zero.");
}
// Return the page with the payment schedule or error messages
return Page();
}
31 Replies
I got the error in the lines where i try to populate object data again on the page <div class="carousel-inner">
@for (var i = 0; i < Model.Property.URL.Count; i++)
{
<div class="carousel-item @(i == 0 ? "active" : "")">
<img class="d-block w-100" src="@Model.Property.URL[i]" alt="Property image @(i + 1)">
</div>
}
I tried using sessions and serialising object but it didnt help. Maybe i used it in a wrong way
Well, do you set the
Property
, and its URL
property when you POST?
'Cause I don't see you doing that
(also, use $code to post code)To post C# code type the following:
```cs
// code here
```
Get an example by typing
$codegif
in chat
For longer snippets, use: https://paste.mod.gg/I am setting Property in my OnGet method, it should stay throught my page, its declared in my page code. But I am not sure about URL..
thanks
The requests are stateless
What it means, is each request you make has a completely clean slate
Everything gets reset when you do a POST request
Doesn't matter what you set when handling a GET
Similarly, everything resets when you do a GET request, everything you set with any other request gets reset
i tried calling OnGet method in the beginning of the POST request and in the end of it, also i tried using sessions to keep all necessary Data but it still thrown null exception, that my Property is empty
I don't see you call
OnGet
anywhere inside of your OnPost
In the snippet i shared i dont call it, i mean i did it before. Let me do it once again and ill share the code again
$code
To post C# code type the following:
```cs
// code here
```
Get an example by typing
$codegif
in chat
For longer snippets, use: https://paste.mod.gg/I am calling 'GET' before returning Page()
same null ex thrown
And actually i got the same error among all of my POST requests in my website and unfortunately i cant solve it with chat gpt or bing
Well, make sure that
pS.GetProperty()
doesn't return null
And that whatever it does return, has the necessary propertyi have unittest for it and i debugged it in OnGet, it returns correct property object with correct properties belonging to object
Huh, aight
What's
pS.GetProperty()
?It is the method of PropertyService, where I inject PropertyDAL of interface IPropertyDAL
I mean, sure, but what's the code?
I'll be more clear maybe. I'm wondering if it's maybe some async issues, like an
async void
method somewhere, or an unawaited async call
That's the only other situation where I can see a page be rendered before the model's properties are set
It is just method that returns Property type object
same for service, just returns result of this method
What code is inside of this method?
Just SQL query that retrieves Property object with given id
lenght of method exceeds max allowed here
Oof
Any suspicious async code?
What I mentioned,
async void
, unawaited async methods, .Result
, etc?nothing like that
Huh, okay, let's try something... Make your
OnPost...
method async Task<IActionResult>
and add await Task.Delay(1000);
between OnGet(id)
and return Page();
this is the method, i cropped out all of the properties of the objects
same error
I feel like it dont even get to the OnPost method
Definitely not async issues, then
I'm out of ideas
Right, how do you even call this method?
<form method="post" asp-page-handler="CalculateMortgage">
Can you just name it
OnPost
and skip the asp-page-handler
?
Or do you have another OnPost
method already?
Also, did you try using the debugger?yep, i also have another 2 OnPost methods
I feel like stepping through the code with a debugger would answer a lot of questions, in hindsight lol
yes, i put the breakpoint everywhere inside OnPost
Do they get hit?
But it didnt hit
After i click the button inside Post on page, it throws an error that Property is null, but breakpoint is not hit