Web Loan Calculator C# ASP Project

This is another test project that does loan amortization. I had to do some quick learning on the loan amount, interest rate, and duration formula. I’m experimenting with different ways to get things done in the back-end code then having the results, work, etc.., display on the webpage. I’ll be getting into creating full sites in the next few posts. However these are just static pages that just display functionality.

I’ve also added conditions to the page that the user has to fill out all of the required fields otherwise errors will display. I’m also playing around with different ways of getting the form data and saving it for later use.

Default.aspx & Error Display Pages

WebLoanCalculatorMainPage WebLoanCalculatorError

Default.aspx Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Web Loan Calculator</title>
    <style type="text/css">
        .style1
        {
            width: 152px;
        }
    </style>
</head>
<body>
    <form id="webLoanCalculator" runat="server">
    <asp:HiddenField ID="loanAmountHiddenField" runat="server" />
    <asp:HiddenField ID="interestRateHiddenField" runat="server" />
    <asp:HiddenField ID="numberOfPaymentsHiddenField" runat="server" />
    <asp:HiddenField ID="loanPaymentAmountHiddenField" runat="server" />
    <table style="width: 100%;">
        <tr>
            <td class="style1">
                <asp:Label ID="webLoanCalculatorLabel" runat="server" 
                    Text="Web Loan Calculator"></asp:Label>
            </td>
        </tr>
        <tr>
            <td class="style1">
                &nbsp;
            </td>
            <td>
                &nbsp;
            </td>
        </tr>
        <tr>
            <td class="style1">
                <asp:Label ID="loanAmountLabel" runat="server" Text="Loan Amount:"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="loanAmountTextBox" runat="server" ToolTip="Enter Numbers Only"></asp:TextBox>
                <asp:Label ID="loanAmountRequiredLabel" runat="server" ForeColor="Red" 
                    Text="*Required Field (Only Numbers)" Visible="False"></asp:Label>
            </td>
        </tr>
        <tr>
            <td class="style1">
                <asp:Label ID="interestRateLabel" runat="server" Text="Interest Rate:"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="interestRateTextBox" runat="server" 
                    ToolTip="Enter Numbers Only"></asp:TextBox>
                <asp:Label ID="interestRateRequiredLabel" runat="server" ForeColor="Red" 
                    Text="*Required Field (Only Numbers)" Visible="False"></asp:Label>
            </td>
        </tr>
        <tr>
            <td class="style1">
                <asp:Label ID="numberOfPaymentsLabel" runat="server" Text="Number Of Payments:"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="numberOfPaymentsTextBox" runat="server" 
                    ToolTip="Enter Numbers Only"></asp:TextBox>
                <asp:Label ID="numberOfPaymentsRequiredLabel" runat="server" ForeColor="Red" 
                    Text="*Required Field (Only Numbers)" Visible="False"></asp:Label>
            </td>
        </tr>
        <tr>
            <td class="style1">
                <asp:Button ID="calculateButton" runat="server" Text="Calculate" 
                    ToolTip="Calculate Payments" />
            </td>
            <td>
                <asp:Label ID="loanPaymentAmountLabel" runat="server" Text="..." 
                    Visible="False"></asp:Label>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

Default.aspx Code Behind Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    //Private class variables.
    private bool _isError = false;      //Bool used as a flag to check for errors.

    protected void Page_Load(object sender, EventArgs e)
    {
        //****Form Button Lambda Expressions****
        //Lambda expression for the Calculate button on Default.aspx
        calculateButton.Click += (from, ea) => getFormData();
    }

    //****Custom methods****
    //Method used to get the data entered from the user on the form.
    private void getFormData()
    {
        //Method variables used to store converted hidden field data.
        double loanAmount = 0.0;
        double interestRate = 0.0;
        int numberOfPayments = 0;

        //Resetting the required fields.
        loanAmountRequiredLabel.Visible = false;
        interestRateRequiredLabel.Visible = false;
        numberOfPaymentsRequiredLabel.Visible = false;

        //Checking to make sure something was typed in the loan amount textbox.
        if (loanAmountTextBox.Text.Length > 0)
        {
            //Saving the loan amount textbox entry to the hidden field value.
            loanAmountHiddenField.Value = loanAmountTextBox.Text;

            //Trying to convert the hidden field value. If not notifying the user.
            if (!double.TryParse(loanAmountHiddenField.Value, out loanAmount))
            {
                loanAmountRequiredLabel.Visible = true;
                _isError = true;
            }
        }
        //Displaying the error user notification if nothing is in the loan amount textbox.
        else
        {
            loanAmountRequiredLabel.Visible = true; 
            _isError = true;
        }

        //Checking to make sure something was typed in the interest rate textbox.
        if (interestRateTextBox.Text.Length > 0)
        {
            //Saving the textbox entry to the hidden field value.
            interestRateHiddenField.Value = interestRateTextBox.Text;

            //Trying to convert the hidden field value. If not notify the user.
            if (!double.TryParse(interestRateHiddenField.Value, out interestRate))
            {
                interestRateRequiredLabel.Visible = true;
                _isError = true;
            }
        }
        //Displaying the error user notification if nothing is in the interest rate textbox.
        else
        {
            interestRateRequiredLabel.Visible = true; 
            _isError = true;
        }

        //Checking to make sure something was typed in number of payments textbox.
        if (numberOfPaymentsTextBox.Text.Length > 0)
        {
            //Saving the textbox entry to the hidden field value.
            numberOfPaymentsHiddenField.Value = numberOfPaymentsTextBox.Text;

            //Trying to convert the hidden field value. If not notify the user.
            if (!int.TryParse(numberOfPaymentsHiddenField.Value, out numberOfPayments))
            {
                numberOfPaymentsRequiredLabel.Visible = true;
                _isError = true;
            }
        }
        //Displaying the error user notification if nothing is in the number of payments textbox.
        else
        {
            numberOfPaymentsRequiredLabel.Visible = true;
            _isError = true;
        }

        //If there are no errors from the form entries the proceed with the calculations.
        if (!_isError)
        {
            //Calculating the loan payment amount, rounding at the last 2 digits, and storing the value in the hidden field.
            loanPaymentAmountHiddenField.Value = Math.Round(calculatePayment(interestRate, loanAmount, numberOfPayments), 2).ToString();
            
            //Displaying the loan payment amount from the hidden field value.
            loanPaymentAmountLabel.Visible = true;
            loanPaymentAmountLabel.Text = "Monthly Payment Amount: $" + loanPaymentAmountHiddenField.Value;
        }
    }

    //Method used to calculate the payment amount.
    private double calculatePayment(double interestRate, double loanAmount, int numberOfMonthlyPayments)
    {
        //Making sure we have valid data.
        if (interestRate > 0 && loanAmount > 0 && numberOfMonthlyPayments > 0)
        {
            //Checking the interest rate format, and divide into monthly percentage rate accordingly.
            if (interestRate > 0)
                interestRate /= 1200;
            else
                interestRate /= 12;

            //Calculate and return the loan payment amount.
            return (interestRate + (interestRate / (Math.Pow(1 + interestRate, numberOfMonthlyPayments) - 1))) * loanAmount;
        }
        else
            return 0;
    }
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s