0

net MVC, i searched on too many sites to fetch data from database into Listbox but i didn't get any proper answer,

I every site there is a hardcoded example for List<> like this,

    public SelectList GetAllCountryList()
    {
        List<Country> objcountry = new List<Country>();
        objcountry.Add(new Country { Id = 1, CountryName = "India" });
        objcountry.Add(new Country { Id = 2, CountryName = "USA" });
        objcountry.Add(new Country { Id = 3, CountryName = "Pakistan" });
        objcountry.Add(new Country { Id = 4, CountryName = "Nepal" });
        SelectList objselectlist = new SelectList(objcountry, "Id", "CountryName");
        return objselectlist;
    }

this id the hard coded but i want to fetch it from db and i know i have to apply query like this

public List<Country> allname = new List<Country>
{
    //query
};

but i dont know how should i use it,or whether this is correct or not

please help to solve this

2
  • 1
    How you make a database call. What is the Repository do you use? Are you using Entity Framework/any/your own DAL? Commented Apr 28, 2014 at 9:03
  • i m using Entity Framework Commented Apr 28, 2014 at 9:18

3 Answers 3

1

In repository you can create like this,

public IQueryable<Country> GetCountries()
    {
        return from country in _db.Countries
               orderby country.Name ascending
               select country;
    }

In Controller:

In controller Get view you create one viewdata and assign the values into that. No need to create in list..

ViewData["Countries"] = new SelectList(_repository.GetCountries(), "Id", "Name");

You want to show these all into view means,

<%: Html.DropDownList("Countries" + i.ToString(), new SelectList(countries, "Id", "Name"))%>

Hope atleast you can get idea.

Sign up to request clarification or add additional context in comments.

Comments

0

There are 2 things you need to know.

  1. How to get data out of a database into a List in C#.
  2. How to get a List into your model for display on the page.

The MVC Music Store Tutorial at http://www.asp.net/mvc/tutorials/mvc-music-store covers both of these. It takes a few hours to work through but it will save you a lot more time than it costs.

But for data access, many people use https://code.google.com/p/dapper-dot-net/ instead of EntityFramework

Comments

0

If you are using Entity Framework

public class YouController:Controller
{
  private YourDBContext db = new YourDBContext();

  public SelectList GetAllCountryList()
  {
    var countries= db.Countries.ToList();
    SelectList objselectlist = new SelectList(countries, "Id", "CountryName");
    return objselectlist;
  }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.