MrProgram
MrProgram

Reputation: 5242

Returning list of objects from controller to view

The code below gives me "Object reference not set to an instance of an object". I know it's because the model is not created, but I can't understand why? Why doesn't the foreach loop in AnnuityDetail.cshtml loop through cList which I am creating and sending from Controller?

Controller action:

public ActionResult AnnuityDetail(FormCollection form)
    {
        List<Calculation> cList = new List<Calculation>();
        Calculation calc = new Calculation();
        calc.Date = Convert.ToDateTime(form["startdate"]);
        calc.InvoiceAmount = 2000;
        calc.InterestRate = Convert.ToDouble(form["InterestRate"]);
        calc.InterestAmount = (Convert.ToDouble(form["PresentValue"]) * Convert.ToDouble(form["InterestRate"]) / 360 * 30);
        calc.Amortization = (2000 - (Convert.ToDouble(form["PresentValue"]) * Convert.ToDouble(form["InterestRate"]) / 360 * 30));
        calc.PresentValue = Convert.ToDouble(form["PresentValue"]) - calc.Amortization;
        calc.StartValue = Convert.ToDouble(form["PresentValue"]);
        cList.Add(calc);
        for (int i = 0; i < Convert.ToInt32(form["PaymentPeriods"]); i++)
        {
            Calculation calcBefore = cList.Last();
            calc = new Calculation();
            calc.Date = calcBefore.Date.AddMonths(1);
            calc.InvoiceAmount = 2000;
            calc.InterestRate = Convert.ToDouble(form["InterestRate"]);
            calc.InterestAmount = (calcBefore.PresentValue * calc.InterestRate / 360 * 30);
            calc.Amortization = (calc.InvoiceAmount - (calcBefore.PresentValue * calc.InterestRate / 360 * 30));
            calc.PresentValue = calcBefore.PresentValue - calc.Amortization;
            cList.Add(calc);
        }
        return View(cList);
    }

View1 (with a form)

@using (Html.BeginForm("AnnuityDetail", "Calculation")) //Runs AnnuityDetail
{
    <div class="calculateBox">
                            <label for="calcOption">Choose value to calculate:</label>
                            <select form="anFormCalcInput" id="calcOption" title="Choose what value you want to calculate">
                                <option value="anPMT">Payment (PMT)</option>
                                <option value="anI">Interest (I)</option>
                                <option value="anFV">Future value (FV)</option>
                                <option value="anPV">Present value (PV)</option>
                            </select>
                        </div>
                        <div class="calculateBox" background-color="#777777">
                            @Html.Label("Present value (PV)")
                            @Html.TextBox("PresentValue")
                            @Html.Label("Future value")
                            @Html.TextBox("FutureValue")
                            @Html.Label("Interest rate")
                            @Html.TextBox("InterestRate") <br />
                            <input type="radio" name="advanceOrArrears" id="inAdvance" value="inAdvance" /> In advance<br />
                            <input type="radio" name="advanceOrArrears" id="inArrears" value="inArrears" /> In arrears
                        </div>
                        <div class="calculateBox">
                            <label for="startDate">Start date:</label>
                            <input type="date" id="anStartDate" name="startdate" title="Choose start date for your calculation" /><br />
                            @Html.Label("Payment frequency")
                            <select form="anFormCalcInput" id="anPmtFreq" title="Choose the payment frequency, for example: Every month">
                                <option value="Monthly">Monthly</option>
                                <option value="Quarterly">Quarterly</option>
                                <option value="Yearly">Yearly</option>
                            </select><br /><br />
                            @Html.Label("No of payment periods")
                            @Html.TextBox("PaymentPeriods")
                            @Html.Label("Date time convention")
                            <select form="anFormCalcInput" id="anDTC" title="Choose your Date time convention">
                                <option value="360360">360/360</option>
                                <option value="365365">365/365</option>
                            </select><br /><br />
                            <input type="submit" id="anCalcBtn" class="calcBtn" name="anSubmitBtn" value="Calculate" title="Calculate your calculation" />
                        </div>
}

View2(AnnuityDetail):

@model IEnumerable<CalcFactory.Models.Calculation>
<table cellspacing="0" width="80%" id"detailTable">
<thead>
    <tr>
        <th>
            Row
        </th>
        <th>
            Date
        </th>
        <th>
            Invoice amount
        </th>
        <th>
            Interest rate
        </th>
        <th>
            Interest amount
        </th>
        <th>
            Amortization
        </th>
        <th>
            Capital balance
        </th>
        <th></th>
    </tr>
</thead>
@{var rowID = 1;}
@{var cellID = 1;}
@foreach (var item in Model) { //In this loop I get my error message, it can't find cList objects
    <tr id="@rowID">
        <td align="center">
            @rowID
        </td>
        <td align="center" id="A-@cellID">
            @Html.DisplayFor(modelItem => item.Date)
        </td>
        <td align="center" id="B-@cellID">
            @Html.DisplayFor(modelItem => item.InvoiceAmount)
        </td>
        <td align="center" id="C-@cellID">
            @Html.DisplayFor(modelItem => item.InterestRate)
        </td>
        <td align="center" id="D-@cellID">
            @Html.DisplayFor(modelItem => item.InterestAmount)
        </td>
        <td align="center" id="E-@cellID">
            @Html.DisplayFor(modelItem => item.Amortization)
        </td>
        <td align="center" id="F-@cellID">
            @Html.DisplayFor(modelItem => item.PresentValue)
        </td>
    </tr>
    rowID++;
    cellID++;
}

Upvotes: 0

Views: 135

Answers (1)

samy
samy

Reputation: 14962

Your form doesn't contain any field for "PaymentPeriods" so the value isn't initialized. The for loop hits its end condition immediately.

If PaymentPeriods should come from the form but not be editable try adding a hidden field with the value you need, but should it be on the client at all?


Shouldn't your @Html.DisplayFor(modelItem => item.Date) be @Html.DisplayFor(item => item.Date) instead? modelItem is not something used anywhere is it?


Could you please try changing the var item to Calculation item and see if the properties are still not resolved?

@foreach (Calculation item in Model) { //In this loop I get my error message, it can't find cList objects
    <tr id="@rowID">
        <td align="center">
            @rowID
        </td>
        <td align="center" id="A-@cellID">
        @Html.DisplayFor(item => item.Date)
    </td>

Upvotes: 2

Related Questions