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
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
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
Angius
Angius12mo ago
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)
MODiX
MODiX12mo ago
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/
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
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
Angius
Angius12mo ago
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
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
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
Angius
Angius12mo ago
I don't see you call OnGet anywhere inside of your OnPost
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
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
public IActionResult OnPostCalculateMortgage(int? id)
{
if (!ModelState.IsValid)
{
return Page();
}

ICalculateStrategy strategy;
if (AmountToBorrow > MaximumLoan * 0.5m)
{
strategy = new FixedRateStrategy();
}
else
{
strategy = new FloatingRateStrategy();
}

Property.Calculator.SetStrategy(strategy);

try
{
List<string> paymentSchedule = Property.Calculator.CalculateMonthlyPayment(AmountToBorrow, LoanTerm);

ViewData["PaymentSchedule"] = paymentSchedule;
}
catch (InvalidOperationException ex)
{
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.");
}
OnGet(id);
return Page();
}
public IActionResult OnPostCalculateMortgage(int? id)
{
if (!ModelState.IsValid)
{
return Page();
}

ICalculateStrategy strategy;
if (AmountToBorrow > MaximumLoan * 0.5m)
{
strategy = new FixedRateStrategy();
}
else
{
strategy = new FloatingRateStrategy();
}

Property.Calculator.SetStrategy(strategy);

try
{
List<string> paymentSchedule = Property.Calculator.CalculateMonthlyPayment(AmountToBorrow, LoanTerm);

ViewData["PaymentSchedule"] = paymentSchedule;
}
catch (InvalidOperationException ex)
{
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.");
}
OnGet(id);
return Page();
}
Angius
Angius12mo ago
$code
MODiX
MODiX12mo ago
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/
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
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
Angius
Angius12mo ago
Well, make sure that pS.GetProperty() doesn't return null And that whatever it does return, has the necessary property
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
i have unittest for it and i debugged it in OnGet, it returns correct property object with correct properties belonging to object
Angius
Angius12mo ago
Huh, aight What's pS.GetProperty()?
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
It is the method of PropertyService, where I inject PropertyDAL of interface IPropertyDAL
Angius
Angius12mo ago
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
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
public Property GetPropertyDetails(int? id)
public Property GetPropertyDetails(int? id)
It is just method that returns Property type object same for service, just returns result of this method
Angius
Angius12mo ago
What code is inside of this method?
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
Just SQL query that retrieves Property object with given id lenght of method exceeds max allowed here
Angius
Angius12mo ago
Oof Any suspicious async code? What I mentioned, async void, unawaited async methods, .Result, etc?
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
nothing like that
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();

string query = "SELECT * FROM Properties WHERE PropertyID = @id";

using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.Add(new SqlParameter("@id", id));

using (SqlDataReader reader = command.ExecuteReader())
{

while (reader.Read())
{
List<string> urlList = !string.IsNullOrEmpty(urls) ? urls.Split(';').ToList() : new List<string>();

return new Property(pId, name, location, price, type, description, urlList, lat, lng);
}
}
}
return null;
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();

string query = "SELECT * FROM Properties WHERE PropertyID = @id";

using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.Add(new SqlParameter("@id", id));

using (SqlDataReader reader = command.ExecuteReader())
{

while (reader.Read())
{
List<string> urlList = !string.IsNullOrEmpty(urls) ? urls.Split(';').ToList() : new List<string>();

return new Property(pId, name, location, price, type, description, urlList, lat, lng);
}
}
}
return null;
}
Angius
Angius12mo ago
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();
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
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
Angius
Angius12mo ago
Definitely not async issues, then I'm out of ideas Right, how do you even call this method?
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
<form method="post" asp-page-handler="CalculateMortgage">
Angius
Angius12mo ago
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?
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
yep, i also have another 2 OnPost methods
Angius
Angius12mo ago
I feel like stepping through the code with a debugger would answer a lot of questions, in hindsight lol
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
yes, i put the breakpoint everywhere inside OnPost
Angius
Angius12mo ago
Do they get hit?
CurlyRed(Serzhio)
CurlyRed(Serzhio)OP12mo ago
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
Want results from more Discord servers?
Add your server