I have a list in the controller as follows:
public class TruckData
{
public string Truck{ get; set; }
}
var truckdat = (from p in KowaDataContext.tblTrucks
orderby p.Truck
select new TruckData {Truck= p.Truck});
var trucklist = truckdat.ToList();
ViewBag.TrckList= trucklist;
The View looks like the following:
@foreach (Data.Rep.Controllers.TruckController.TruvckData item in ViewBag.TrckList)
{
<tr>
<td>
@item.Truck
</td>
</tr>
}
My question is, how can I pass the list to the view without using the class:
public class TruckData
{
public string Truck{ get; set; }
}
so that my list looks like the following: Notice how the reference to TruckData is gone below:
var truckdat = (from p in KowaDataContext.tblTrucks
orderby p.Truck
select new {Truck= p.Truck});
var trucklist = truckdat.ToList();
ViewBag.TrckList= trucklist;
I am not sure how the foreach in the view will look like. I tried what is shown below but was giving me a problem.
@foreach (var item in ViewBag.TrucksSelectList)
No, this is not possible. You cannot pass anonymous objects to views. The reason for this is that anonymous objects are emitted as internal by the compiler. And since ASP.NET dynamically compiles views into a separate assembly they do not have access to this model.
That would be against all good practices => you need to use a view model:
and then in the view:
And since you have a list of strings you could probably use that as model:
and then in the view:
I would also very strongly recommend you to get rid of ViewBag and use strongly typed view models:
and then:
And introducing a display template for the TruckData type (
~/Views/Shared/DisplayTemplates/TruckData.cshtml):you can even get rid of the ugly and useless foreach loop in your main view: