Reputation: 3965
I have the following in my controller (HomeController.cs) which generates a Bikes variable that I'm trying to pass into the view (Index.cshtml):
public string xmlPath = HostingEnvironment.MapPath("~/App_Data/bikes.xml");
public ActionResult Index()
{
// get the most recent 20 records
XDocument xml = XDocument.Load(xmlPath);
var bikes = from b in xml.Descendants("Photo")
select new
{
date = (DateTime)b.Element("Date"),
staffno = (Int32)b.Element("StaffNo"),
file = (string)b.Element("File"),
crimeref = (string)b.Element("CrimeRef")
};
var Bikes = bikes.ToList();
return View(Bikes);
}
I now want to loop through the results and display them on the page using Razor using the following code:
@foreach (var bikes in Bikes))
{
<tr>
<td>@(bikes.date)</td>
<td>@(bikes.staffno)</td>
<td>@(bikes.file)</td>
<td>@(bikes.crimeref)</td>
</tr>
}
However, despite passing the Bikes variable into the View() command in the controller, the Bikes list is not accessible from within my view.
Any suggestions would be very welcome, thank you :)
Upvotes: 0
Views: 1085
Reputation: 684
It would be named 'Model' inside the view. When you pass an object to the view it is the model. So your view can either be strongly typed (there will be a line saying that its model inherits from a specific class - its usually done in the wizzard when you create a view), or if you choose not to assign a specific class for the model the Model object will be of type dynamic, which means that it will be evaluated run time, so the compilator will allow you to call everything on it. Long story short, try
@foreach (var bikes in Model))
{
<tr>
<td>@(bikes.date)</td>
<td>@(bikes.staffno)</td>
<td>@(bikes.file)</td>
<td>@(bikes.crimeref)</td>
</tr>
}
Unfortunately I work with aspx so I cant be sure that Im right, but try it this way or find information about how are models passed to the view in razor
Upvotes: 0
Reputation: 82096
Well firstly, in your view you wouldn't have a variable called Bikes
, the view has a property named Model
which is a reference to the data you pass in. Secondly, I am not sure MVC supports passing anonymous types to the view, instead you should create a view model specifically for the data required
public class BikeViewModel
{
public DateTime Date { get; set; }
public int StaffNo { get; set; }
public string File { get; set; }
public string CrimeRef { get; set; }
}
...
var bikes = (from b in xml.Descendants("Photo")
select new BikeViewModel
{
Date = (DateTime)b.Element("Date"),
StaffNo = (Int32)b.Element("StaffNo"),
File = (string)b.Element("File"),
CrimeRef = (string)b.Element("CrimeRef")
}).ToList();
return View(bikes);
Then in your view
@model List<BikeViewModel>
...
@foreach(var bike in Model)
{
<tr>
<td>@(bike.Date)</td>
<td>@(bike.StaffNo)</td>
<td>@(bike.File)</td>
<td>@(bike.CrimeRef)</td>
</tr>
}
Upvotes: 2