0

I have a class, Farm, which contains a list of classes of type Animal.

public class Farm {
    public list<Animal> Animals;
    // other members..
} 
public class Animal {
    public string Name;
    public string Family;
}

I would like to make a createOrEdit view for my Farm object, and I'd like to use DropDownLists for the Animal's Name and Family. The choices are coming from a database.

When I pass the Animal model to the view for editing I'd like to have the DropDownLists somehow match the properties for each animal and set the selected values of the lists.

I've tried lots of things like this:

@for(int i = 0; i < Model.Animals.Count; i++)
{ 
    @Html.DropDownListFor(model => model.Animals[i].Name, Model.AnimalNames) 
    // where Model.AnimalNames is a SelectList

    @Model.Animals[i].Name // (for testing) this properly displays the name I want to be selected in the list
}

I've seen a bunch of suggestions on this site for creating SelectLists in the controller, iterating through each item and setting the selected property where appropriate. But there's gotta be a cleaner way.. what if I have 100 Animals on my farm. It doesn't seem reasonable to create 200 SelectLists in the controller, iterate through each of them to match up the selected values, and then pass that to the view.

So, is there a simple way for me to take that Animal.Name[i] value and find its matching listitem in the DDL?

Thanks!!

4

1 に答える 1

0

foreach ループ内で次のことができます。

@for(int i = 0; i < Model.Animals.Count; i++)
{ 
   var original = Model.AnimalNames;
   var animalSelected = new SelectList(original.Items, original.DataValueField, original.DataTextField, model.Animals[i].Name);

   @Html.DropDownListFor(model => model.Animals[i].Name, animalSelected)

}

このように、コントローラーで AnimalNames を使用して SelectList を 1 つだけ作成し、ビューで、それぞれに選択された値を使用して SelectList を作成します。

各アイテムの現在の値を表示する必要がある編集可能なアイテムのリストを使用する場合、このアプローチを使用します。

于 2013-01-25T20:48:35.100 に答える