asp.net - DropDownListFor a collection not selecting value -


I am using a strictly typed view with a custom realm. This view-model is a collection of books.

  Public ILIST & lt; Books & gt; Books {receive; Private set; }   

I am also passing a selection list to see. Although the dropdown listfor assistant class does not automatically select the default value of the book.

  @ Html.DropDownListFor (m => Model.books [i] .AuthorID, Model.Author as SelectList)   

Everything else Works, eg this selected value passes back to the controller.

I found a workaround by creating a selection list in the view-list:

  @ html.DropDownListFor (m => Model.Books [i] .AuthorID, New SelectList (Model.AuthorList, "Value", "Text", @ Model.Books [i] .AuthorID.ToString ()))   

Although I do not want to implement this solution Is there a simpler solution, is such a way that the view can handle the value from the collection?

you should pass the list of authors as part of your model As you have in your solution, you can generate a selection list in the controller, however, there is no need to create a list in the view. Something like this:

  @ html.DropDownListFor (m => Model Books [i]. Author, Model.AuthorList)   

This work You will create a list in the controller:

  var model = new view mode () {AuthorList = new SelectList (Model.AuthorList, "Value", "Text")}};   

and it will handle setting selected items automatically.

Why your model for this The author is not working as a selector, I'm guessing the model. The author is not a list of author names and IDs. This is probably a domain object and is canceling castings using it as .

Comments