Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to retrieve properties from Viewbag item

Tags:

c#

asp.net-mvc

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'
like image 673
user3206357 Avatar asked Jan 23 '26 01:01

user3206357


1 Answers

You have some errors in your code.

  1. You should create 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.
  2. I can suggest you don't use 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>    
}
like image 108
alexmac Avatar answered Jan 24 '26 14:01

alexmac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!