Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
/// Get All Countries
     /// </summary>
     /// <returns></returns>
     public IQueryable GetAllCountry()
     {
         using (Context context = new Context())
         {
             var countries = context.COUNTRY.Select(c => new
             {
                 country = new
                 {
                     ID = c.ID,
                     Description = c.DESCRIPTION,
                     CountryPhoneCode = c.COUNTRY_PHONE_CODE,
                     Currency = c.CURRENCY.CURRENCY,
                     Language = context.LANGUAGE.Where(l => l.COUNTRY_ID == c.ID).Select( l => new { lang = l.DESCRIPTION }).Distinct()
                 }
             });

             return countries;
         }

     }


C#
        // GET: /Country/ My controller 

        public ActionResult DisplayCountries()
        {
            DAL library = new DAL();

            var country = library.GetAllCountry();
            ViewBag.countries = country;
            return View("DisplayCountries");
        }

//My View

@{
    ViewBag.Title = "DisplayCountries";
}

Country list

   @{
       var countries = ViewBag.countries;

        foreach (var country in countries)
        {
            @country.country.ID; // property country is not defined. error!
        }
   }


Problem:
How do I display the data sent from controller to View. Do I need to create a separate class to display the data? Is there no other way to do this ? What are the alternatives if I dont want to use ViewBag ?
Posted

1 solution

Alternative for viewbag is send the countries object as a model to view and add strogly typed view.
and the code will be ,

C#
//Controller
 public ActionResult DisplayCountries()
        {
            DAL library = new DAL();
 
            var country = library.GetAllCountry();           
            return View("DisplayCountries",country);
        }

//View
@model Demo.Counties

<ul>
@foreach(var country in Model.Countries)
{
 <li>country.Description</li>
}
</ul>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900