0

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.

image

1
  • May be it would help if you can post what you tried. Commented Dec 10, 2015 at 15:21

1 Answer 1

2

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!

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

4 Comments

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?
view page is showing error near dropdown i dont know why?
What is the error? This exact code rendered a droplist in my test.
The class country in the model page is it your model class ?

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.