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
Radio-ON-(Serzhio)
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
Angius6mo 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
MODiX6mo 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/
Radio-ON-(Serzhio)
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
Angius6mo 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
Radio-ON-(Serzhio)
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
Angius6mo ago
I don't see you call OnGet anywhere inside of your OnPost
Radio-ON-(Serzhio)
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
Angius6mo ago
$code
MODiX
MODiX6mo 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/
Radio-ON-(Serzhio)
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
Angius6mo ago
Well, make sure that pS.GetProperty() doesn't return null And that whatever it does return, has the necessary property
Radio-ON-(Serzhio)
i have unittest for it and i debugged it in OnGet, it returns correct property object with correct properties belonging to object
Angius
Angius6mo ago
Huh, aight What's pS.GetProperty()?
Radio-ON-(Serzhio)
It is the method of PropertyService, where I inject PropertyDAL of interface IPropertyDAL
Angius
Angius6mo 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
Radio-ON-(Serzhio)
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
Angius6mo ago
What code is inside of this method?
Radio-ON-(Serzhio)
Just SQL query that retrieves Property object with given id lenght of method exceeds max allowed here
Angius
Angius6mo ago
Oof Any suspicious async code? What I mentioned, async void, unawaited async methods, .Result, etc?
Radio-ON-(Serzhio)
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
Angius6mo 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();
Radio-ON-(Serzhio)
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
Angius6mo ago
Definitely not async issues, then I'm out of ideas Right, how do you even call this method?
Radio-ON-(Serzhio)
<form method="post" asp-page-handler="CalculateMortgage">
Angius
Angius6mo 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?
Radio-ON-(Serzhio)
yep, i also have another 2 OnPost methods
Angius
Angius6mo ago
I feel like stepping through the code with a debugger would answer a lot of questions, in hindsight lol
Radio-ON-(Serzhio)
yes, i put the breakpoint everywhere inside OnPost
Angius
Angius6mo ago
Do they get hit?
Radio-ON-(Serzhio)
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
More Posts
✅ hey. im new to learning asp.net and was wondering if anyone had any suggestions as where to start?just any ideas of things to do/ things to watch would be great!Measuring sub-millisecond execution time with Methodtimer.FodyI am using https://github.com/Fody/MethodTimer to measure code execution time. The function I am try✅ How to SimplifyI have this https://gist.github.com/IXLLEGACYIXL/399c51cf0341188bdc4e02a820c34ce0 I need the generic✅ Blazorserver - Value after manual db-update not changing after new fetchHello, I setup a blazorserver project and implemented a db connection and wanted to load user data.How do I using Roslyn with correct version of .net# How do I using Roslyn with correct version of .net Hello I'm new to C# and roslyn usage, I'm tryiNuget SourceRoot | Microsoft.Build.Framework.ITaskItem | MSB4094 ErrorI am in the middle of my Intro to C# course and the only error I have is this error that is actuallyCan someone explain this variable and how this works?I'm looking over this code https://github.com/sebinside/PremiereClipboard/blob/master/PremiereClipboDependency Injection - Data ExporterI’ve been trying to wrap my head around dependency injection, but I’m struggling to bridge the gap bHTTPS vs HTTPWhen running my .net web api from visual studio via the green 'https' button i get: Yet when publiHow to Speed up training process with gpu ( Image classification )I was following this guide from C# to build a image classification model. Everything works well unti