Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I would like to create a simple drop-down box that displays a list of countries. The data for it comes from the database and is accessed using the entity framework data context. The user should select a country before posting the data back.(simple validation check).

I've created the view model and have also written some code, but I'm not sure about my design and I also need help to complete the code. I've done some search, but I couldn't find a simple way of doing this. Please help. Thanks

View Model - Country.cs

C#
public class Country
{   [Required]
    public int CountryId { get; set; }
    public IEnumerable<SelectListItem> Countries { get; set; }
}

Controller
C#
public ActionResult CountriesDropDown()
{
    using(ctx) 
    {
        var dropdown = (from q in ctx.Countries
                        select new Models.Country 
                         {
                           Id = q.Id,
                    //Need Code to populate the countries properties with country names from the database. 
                          }
    return view();
}

[HttpPost]
public ActionResult AddCountry(Models.Country country)
{
    using(ctx) 
    {
        }
    return view();
}

Countries View

HTML
@model Models.Country

@Html.DropDownListFor(model => model.Country..?..Need code here as well, "please select")
@Html.ValidationFor(...Need code here to make sure the user selects a country)
Posted
Updated 12-Apr-13 0:19am
v5

1 solution

You can also do it by alternate way,follow this one
C#
public class Country
{   [Required]
    public int CountryId { get; set; }
    public string CountryName {get;set:}
}



Controller

C#
public ActionResult CountriesDropDown()
{
    using(ctx) 
    {
        var dropdown = (from q in ctx.Countries
                        select new Models.Country 
                         {
                           Id = q.Id,
                           Name = q,CountryName

                    //Need Code to populate the countries properties with country names from the database. 
                          }
        Viewbag.Country = dropdown;
    return view();
}



Countries View
C#
@model Models.Country
 
@Html.DropDownListFor(model => model.CountryId,new SelectListItem{@Viewbag.Country,CountryName,CountryId}, "please select");
 
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