I have country names in the table with the id for it as shown in image.I want to create a drop down in view page(HTML)using MVC model where the country names should populate in it using C# coding.
1 Answer
You'll probably want to set up a property on your model that you can bind to a droplist. I put together a simple example using your data:
Create a class to represent your country tables:
public class country
{
public string countries { get; set; }
public int id { get; set; }
}
Now populate a list of the data from your table which you should be doing from a call to your database:
var countries = new List<country>();
countries.Add(new country() { id = 1, countries = "ind" });
countries.Add(new country() { id = 2, countries = "usa" });
countries.Add(new country() { id = 3, countries = "uk" });
countries.Add(new country() { id = 4, countries = "pak" });
countries.Add(new country() { id = 5, countries = "britan" });
There are multiple ways to bind your data but a simple method looks like this:
var countriesList = new List<SelectListItem>(
countries.Select(_ => new SelectListItem() {
Text = _.countries,
Value = _.id.ToString() }
)
);
return View(countriesList);
// You can also add countriesList as a property on a bigger model
In your view, you'll want to bind the object you just created. In this scenario, it is simply the Model.
@Html.DropDownList("countries", Model)
Hope this helps, good luck!
4 Comments
anu
i have already given id's in database in a table corresponding columns with id and country name and i want to retrieve them directly to dropdown with the help of id with out writing them again.can i do that?
anu
view page is showing error near dropdown i dont know why?
ohiodoug
What is the error? This exact code rendered a droplist in my test.
anu
The class country in the model page is it your model class ?
