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();
}
{
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();
}