Question

I built a new SelectListItem. I can populate the options, but it won't let me set the Selected Item:

Model Values

Model.Clients.ClientId = 1
Model.Clients.Name = "Company 1"
Model.Clients.ClientId = 2
Model.Clients.Name = "Company 2"
Model.Clients.ClientId = 3
Model.Clients.Name = "Company 3"
Model.Clients.ClientId = 4
Model.Clients.Name = "Company 4"
Model.Clients.ClientId = 5
Model.Clients.Name = "Company 5"

Model.User.Client.ClientId = 3

DropDownListFor

@Html.DropDownListFor(model => model.User.Client, Model.Clients.Select(x => new SelectListItem
{
    Text = x.Name,
    Value = x.ClientId.ToString(),
    Selected = x.ClientId == Model.User.Client.ClientId
    }).ToList(),
    new { @class = "form-control" }
)

Drop Down List HTML

<select class="form-control" id="User_Client" name="User.Client">
    <option value="1">Company 1</option>
    <option value="2">Company 2</option>
    <option value="3">Company 3</option>
    <option value="4">Company 4</option>
    <option value="5">Company 5</option>
</select>

My code should make option 3 the selected item, but it's not.

Was it helpful?

Solution

Try below code:

@Html.DropDownListFor(model => model.User.Client.ClientId, 
new SelectList(Model.Clients,"ClientId","Name", Model.User.Client.ClientId), 
new { @class = "form-control" })

Note: you can not bind Client class for the DropDownList, you need to use property like ClientId.

It's better to add another property for the selected client. like below:

public class yourModel
{
   public int selectedClientId {get;set;}
   //
}

    @Html.DropDownListFor(model => model.selectedClientId, 
    new SelectList(Model.Clients,"ClientId","Name", Model.User.Client.ClientId), 
    new { @class = "form-control" })

OTHER TIPS

try the follwoing

 @Html.DropDownListFor(model  => model.User.Client,
 new SelectList(Model.Clients.ToList(), "ClientId", "Name", Model.User.Client.ClientId))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top