I have a Web API in ASP.NET with OData and I can consume without problems of the service, but I can not get the view to print A table. I'm starting with .NET and with MVC .
Model:
namespace exchange_rates
{
using System;
using System.Collections.Generic;
public partial class CurrentValue
{
public int Id { get; set; }
public System.DateTime Date { get; set; }
public string Currency { get; set; }
public double Rate { get; set; }
}
}
Controller:
namespace exchange_rates.Controllers
{
public class CurrentValuesController : ODataController
{
private db_test_bce_Entities db = new db_test_bce_Entities();
// GET: odata/CurrentValues
[EnableQuery]
public IQueryable<CurrentValue> GetCurrentValues()
{
return db.CurrentValues;
}
// GET: odata/CurrentValues(5)
[EnableQuery]
public SingleResult<CurrentValue> GetCurrentValue([FromODataUri] int key)
{
return SingleResult.Create(
db.CurrentValues.Where(currentValue => currentValue.Id == key)
);
}
}
}
File code WebApiConfig.cs :
namespace exchange_rates
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<CurrentValue>("CurrentValues");
config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
}
}
}
View:
@model IEnumerable<exchange_rates.CurrentValue>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>CurrenciesTable</title>
</head>
<body>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Date)
</th>
<th>
@Html.DisplayNameFor(model => model.Currency)
</th>
<th>
@Html.DisplayNameFor(model => model.Rate)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Date)
</td>
<td>
@Html.DisplayFor(modelItem => item.Currency)
</td>
<td>
@Html.DisplayFor(modelItem => item.Rate)
</td>
</tr>
}
</table>
</body>
</html>
Online error that says @foreach (var item in Model)
:
System.NullReferenceException: Object reference not set as an instance of an object.