Question: Null Object Reference when trying to consume Web Api Data In MVC

Question

Null Object Reference when trying to consume Web Api Data In MVC

Answers 0
Added at 2016-12-30 22:12
Tags
Question

To follow on from a previous post I have made, I am making a web ATM for a university project. For this, I have an MVC application through which most of the cunctionality is based, and an API project, which has a database inside it. I am trying to consume the data from this database and display them in my Index Method currently. However, when I run my solution, I am given a Null Object Reference at the following line of my Index View:

  @foreach (var item in Model.ExcRateList)

I am struggling to figure out why this is not working, and am turning to you good people for a possible solution.

Below is my Index Get Method located in my controller:

   // GET: AtmAccounts
    public ActionResult Index()
    {
        ViewModels.ExcClient ex = new ViewModels.ExcClient();
        ViewBag.listRates = ex.findAll();
        var userID = User.Identity.GetUserId();
        ViewModels.AtmAccountVM atmVm = new ViewModels.AtmAccountVM();
        atmVm.AtmAccountList = db.AtmAccounts.Where(a => a.UserId == userID).ToList();
        atmVm.UserName = User.Identity.GetUserName();
        atmVm.ExcRateList = ViewBag.listRates;
        return View(atmVm);
 }

The parts of which that concern this problem are:

  ViewModels.ExcClient ex = new ViewModels.ExcClient();
        ViewBag.listRates = ex.findAll();

and

atmVm.ExcRateList = ViewBag.listRates;

The View Model AtmAccountVM controls the values passed between my different methods, including that of my API (Or at least, it should):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ATMApplication.Models;
using System.Data.SqlClient;

namespace ATMApplication.ViewModels
{
public class AtmAccountVM
{
    public List<AtmAccount> AtmAccountList { get; set; }
    public List<Transaction> TransactionsList { get; set; }
    public string UserName { get; set; }

    public int Id { get; set; }

    //These variables are used for the various ATM functions accessible to     customers
    public decimal DepositAmount { get; set; }
    public decimal WithdrawAmount { get; set; }
    public decimal TransferAmount { get; set; }
    public string AccTransfer { get; set; }


    // These are Used for the Restful Service
    public int id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public decimal Rate { get; set; }
    public List<ExcRate> ExcRateList { get; set; }





    }
  }    

Following are the view models ExcRate, which stores the data retrieved from the API, and ExcClient which fetches it:

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


namespace ATMApplication.ViewModels
{
public class ExcRate
{
    public int id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public decimal Rate { get; set;}
}
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;



namespace ATMApplication.ViewModels
{
public class ExcClient
{
    private string Base_Url = "http://localhost.57341/api/values";

    public IEnumerable<ExcRate> findAll()
    {


        try
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(Base_Url);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = client.GetAsync("rates").Result;
            if (response.IsSuccessStatusCode)
            {
                var responseData = response.Content.ReadAsStringAsync().Result;
                var Rates = JsonConvert.DeserializeObject<List<ExcRate>>(responseData);
                return Rates;
            }
            return null;
        }
        catch
        {
            return null;
        }
    }
}
}

And finally, here is the Index View the bottom part of which is meant to display this data in a table:

@using ATMApplication.ViewModels
@model ATMApplication.ViewModels.AtmAccountVM


<h2> Accounts Held for Customer: @Model.UserName </h2>

<p>
@Html.ActionLink("Create New Account", "Create")
</p>
<style typw ="text/css">
span {
color: darkcyan;

}

</style>
<div style="background-color:lightyellow; color: black;">


<table class="table">

    <tr>
        <th>
            @Html.DisplayNameFor(model => model.AtmAccountList.First().AccountNumber)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.AtmAccountList.First().AccountBalance)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.AtmAccountList.First().AccType.AccountType)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model.AtmAccountList)
    {

        <tr>

            <td>
                <div style="background-color:lightyellow">
                    @Html.DisplayFor(modelItem => item.AccountNumber)
                </div>
            </td>
            <td>
                <div style="background-color:lightyellow">
                    @Html.DisplayFor(modelItem => item.AccountBalance)
                </div>
            </td>
            <td>
                <div style="background-color:lightyellow">
                    @Html.DisplayFor(modelItem => item.AccType.AccountType)
                </div>
            </td>
            <td>
                <div style="background-color:lightyellow">
                    @Html.ActionLink("Deposit", "Deposit", new { id = item.Id })
                </div>
                <div style="background-color:lightyellow">
                    @Html.ActionLink("Quick Withdraw", "Quick Withdraw", new { id = item.Id })
                </div>
                <div style="background-color: lightyellow">
                    @Html.ActionLink("Withdraw", "Withdraw", new { id = item.Id })
                </div>
                <div style="background-color:lightyellow">
                    @Html.ActionLink("Transfer", "Transfer", new { id = item.Id })
                </div>
                <div style="background-color:lightyellow">
                    @Html.ActionLink("Transactions", "Transactions", new { id = item.Id })
                    <input type="hidden" name="Id" value="@Model.AtmAccountList[0].Id" />
                </div>

            </td>
        </tr>

    }
</table>
</div>

<br />
<br />
<h2>Exchange Rates</h2>
<p>
These are the current exchange rates (in GBP):
</p>
<br/>
<div style="background-color:lightcyan">
<table class="table">
   <tr>

       <th>Currency Code</th>
       <th>Currency Name</th>
       <th>Exchange Rate (GBP)</th>
   </tr>
   @foreach (var item in Model.ExcRateList)
   {
       <tr>
           <td>@item.Code</td>
           <td>@item.Name</td>
           <td>@item.Rate</td>
       </tr>
   }
</table>
</div>
Answers to

Null Object Reference when trying to consume Web Api Data In MVC

Source Show
◀ Wstecz