2

i have a model :

public  class person
 {
   public int id{get;set;}
   public string name{get;set;}
 }

how can i make a drop down list, from list of person in mvc3 razor by this syntax : @Html.DropDownListFor(...) ? what type must be my persons list?

sorry I'm new in mvc3

thanks all

motevalizadeh
  • 5,244
  • 14
  • 61
  • 108
  • possible duplicate of [Populating ASP.NET MVC DropDownList](http://stackoverflow.com/questions/1297399/populating-asp-net-mvc-dropdownlist) – Chase Florell Sep 27 '11 at 15:22

2 Answers2

1

You should translate that to a List<SelectListItem> if you want to use the build in MVC HtmlHelpers.

  @Html.DropDownFor(x => x.SelectedPerson, Model.PersonList)

Alternatively, you can simply make your own in the template:

<select id="select" name="select">
@foreach(var item in Model.PersonList)
{
   <option value="@item.id">@item.name</option>
}
</select>
Tejs
  • 40,736
  • 10
  • 68
  • 86
1
    public class PersonModel
    {           
        public int SelectedPersonId { get; set; }
        public IEnumerable<Person> persons{ get; set; }
    }
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

then in the controller

public ActionResult Index()
{        
    var model = new PersonModel{             
        persons= Enumerable.Range(1,10).Select(x=>new Person{

            Id=(x+1),
            Name="Person"+(x+1)                
        }).ToList()                     <--- here is the edit

    };
    return View(model);//make a strongly typed view
}

your view should look like this

@model Namespace.Models.PersonModel
<div>
   @Html.DropDownListFor(x=>x.SelectedPersonId,new SelectList(Model.persons,"Id","Name","--Select--"))
</div>
Rafay
  • 30,950
  • 5
  • 68
  • 101
  • thanks a lot i test it but in line Html.DropDownListFor(x=>x.SelectedPersonId,new SelectList(Model.persons,"Id","Name","--Select--")) gave this error: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. – motevalizadeh Sep 27 '11 at 16:36
  • it working with me... try it using `.ToList()` i'll update the answer in a bit – Rafay Sep 27 '11 at 16:42
  • thanks but using mades that error if i remove using it works fine ,why with using that error happens? using (KCMDBEntities KCMDB = new KCMDBEntities()) { } – motevalizadeh Sep 27 '11 at 16:59
  • here it is explained http://stackoverflow.com/questions/2884332/asp-net-entity-framework-objectcontext-error/2884343#2884343 – Rafay Sep 27 '11 at 17:18
  • thanks 3nigma you help me very nice your sample was Very helpful.thanks a lot 3nigma – motevalizadeh Sep 27 '11 at 17:40