I am retrieving Name and Id of country from db and setting it in Viewbag. But when I am accessing it from view its throwing error.
Here is C# code:-
var country = from x in db.Territories select new
{
x.Name,
x.ID
};
ViewBag.countries = country;
View Page Code:-
@foreach (var item in ViewBag.countries)
{
<td><label class="control-label">@item.Name</label></td>
}
Error:--
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'Name'
You have some errors in your code.
CountryModel class, and select list of these models in your action, in the case of using anonymus type you couldn't use it in view. ViewBag to pass data to view, the best way is using Model. Model:
public class CountryModel
{
public int Id {get;set;}
public string Name {get;set;}
}
Action:
var countries = (
from x in db.Territories
select new CountryModel
{
Name = x.Name,
Id = x.ID
}).ToList();
return View(countries);
View:
@model List<CountryModel>
@foreach (var item in Model)
{
<td><label class="control-label">@item.Name</label></td>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With