I have a SelectList in my MVC2 model.
In the case that there’s only 1 item in the SelectList I want this one item automatically selected (in my view I add an additional item).
My problem is that I can’t get this single item to be selected.
So the class behind my model has
if (Clients.Count() == 1)
{
Clients.First().Selected = true;
}
But immediately after stepping through this line, if I add a watch to Clients I can see that Selected = null.
In addition, on my View I have
<%:Html.DropDownListFor(c => c.Client, Model.Clients, "-- Select Client --") %>
When the page loads — Select Client — is always selected.
Can anyone explain how I can get the model to correctly mark the item as being selected?
Your view model must have a property Model.Client and it would appear (from the code above) that you’re not setting that value?
Perhaps in the controller action:
Model.Client = Clients.First();
It’s the Model.Client property you need to set though, not the SelectList options.