0

First off, I have been searching for an answer for this and come up with solutions for it, but not matching my exact question regarding automatic generation of dropdownlists (just HOW to make one yourself).

So, the question is. I like to use the scaffolding option in Visual Studio, since it sets up a controller with full CRUD and views that meets my needs.

However, I just ran into a situation where I would like to have a dropdownlist. Is this something that the Scaffolding can create? Or is it in fact something that I have to do myself?

For example I have this model:

public class School
{
    public int SchoolID { get; set; }

    [Required(ErrorMessage = "A value has to be entered.")]
    [StringLength(200)]
    public string Name { get; set; }

    [Required(ErrorMessage = "A value has to be entered.")]
    [StringLength(200)]
    public string MailPrefix { get; set; }

    public int CountryID { get; set; }

    public virtual List<Country> Country { get; set; }
}

So what I am trying to figure out here is what needs to be done to make Visual Studio realize that i want a Dropdownlist created, making it possible to select country, and then save that countryId to the database.

I should point out that I'm also using Entity Framework and the scaffolding option for that in Visual Studio.

Thanks a lot in advance for any info!

Subtractive
  • 500
  • 2
  • 9
  • 19

1 Answers1

1
public List<SelectListItem> CountryListItems {get; set;}
public int CountryId {get; set;}

use above in Model

   Model.CountryListItems= new List<SelectListItem>();
   CountryListItems.Add(new SelectListItem
        {
          Text = "Albania",
          Value = "1"
        });
   CountryListItems.Add(new SelectListItem
        {
            Text = "Bangladesh",
            Value = "2",
            Selected = true
        });
   CountryListItems.Add(new SelectListItem
        {
            Text = "Canada",
            Value = "3"
        });

The code above can be used in controller or other generator model class.

@Html.DropDownListFor(model => model.CountryId, model.CountryListItems, "-- Select Status --")

In View, use the block above.

for further investigation: DropDownList in MVC 4 with Razor

Community
  • 1
  • 1
  • Thanks a lot for taking the time to answer my question! Another user pointed out that this question is almost identical to another, so i marked that as the answer. I apologize for obviously not searching good enough! Thanks again! – Subtractive Aug 18 '16 at 17:22
  • not a problem. i saw that. You don't need to mark this as an answer or vote up. i just thought, i can answer this here. :) have a nice day – Md. Tazbir Ur Rahman Bhuiyan Aug 18 '16 at 17:26