0

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++;
}

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

6 Comments

I'm sorry, I will update form code. PaymentPeriods exists, so the loop should run
But wouldn't that actually mean you are just passing an empty list reference into the view. The loop won't iterate. However the Op is saying that he gets "Object Reference" error @ that line...
@deostroll You're right, i was fixated on the first part of the question asking why the for loop wasn't running. Looking into the updated code
I have tried this action before but then I returned a partialview (and it worked). But now I need this in a view and I get this problem. So I think that the actionmethod is fine except that the foreach doesn't find cList or something
If I use item => item.Date i can't find my property of the Model in the loop EDIT: It's working with everything => item.Date, except for just item =>..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.