2
votes

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

2

2 Answers

1
votes
    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>
1
votes

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>