I have a list of entities in my view model:
public class ViewModel {
public int SelectedItem {get; set;}
public List<Meeting> Meetings {get; set;}
}
public class Meeting {
public int Id {get; set;}
public string Title {get; set;}
public string Info {get; set;}
}
In my view I have a dropdownlist to serve as a listbox (setting the size to 10), and I'm shortcutting the selectlist creation as I've seen in some examples:
@Html.DropDownListFor(model => model.SelectedItem,
new SelectList(Model.Meetings, "Meeting.Id", "Meeting.Title"),
new {@id="itemList"})
This works in my first page load, when Meetings is an empty list. But as soon as Meetings is populated I get a reference is not set to instance of object error. I moved the creation of the selectlist into my controller with a similar thought:
ViewBag.mySelectList = new SelectList(ViewModel.Meetings, "Meeting.Id", "Meeting.Title")
and in the debugger I see that it the selectlist is there and includes the Meetings list, but the results view returns the error. When I create it as I have normally done:
var selList = Meetings.Select(m => new SelectListItem {
Value = m.Id.ToString(),
Text = m.Title}).ToList();
mySelectList = new SelectList(selList, "Value", "Text");
And then return the view model (mySelectList is in the viewmodel for this to work) to the view it works. This seems like the right approach but seeing examples of view code like mine above had me hopeful for smaller view models and controller code. Is there some trick to creating the SelectList on the fly in the Razor page that I'm not seeing?
Replace the strings "Meeting.Id" and "Meeting.Title" with the nameof
expression. There are no quotes for the values in the nameof
expression.
@Html.DropDownListFor(model => model.SelectedItem,
new SelectList(Model.Meetings, nameof(Meeting.Id), nameof(Meeting.Title)),
new {@id="itemList"})
The Razor <select>
tag helper version:
<select id="itemList"
asp-items="@new SelectList(Model.Meetings, nameof(Meeting.Id), nameof(Meeting.Title))"
aria-label="List of meetings"></select>