开发者

DropDownListFor a collection not selecting value

I'm using a strongly typed view with a custom viewmodel. This viewmodel contains a collection of books.

public IList<Books> Books { get; private set; }

I'm also passing a select-list to the view. Howeve开发者_如何学运维r the DropDownListFor helper class doesn't automatically preselect the default value of the book.

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

Everything else works, e.g. it does pass the selected value back to the controller.

I figured out a workaround by creating the select list in the viewmodel:

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

However I don't want to implement this workaround if there is a simpler solution. is there a way that the view can handle values from a collection?


You should be passing the list of authors as part of your model as you have in your workaround. You can generate the select list in the controller however, it isn't a requirement to create the list in the view. Something like:

@Html.DropDownListFor(m => Model.Books[i].AuthorID, Model.AuthorList)

This would work if you create the list in the controller:

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

And it will handle setting the selected item on it's own.

As for why your Model.Author as SelectList isn't working, I'm guessing Model.Author is not a list of author names and IDs. It's probably a domain object and casting it using as is returning null.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜