Aparently this is a simple question already answered on SO but I cannot make it work in my code.

I want to be able to pre select the first element showed on a SelectList on my view.

My Controller:

public ActionResult Create(){
    CostumerRegister rModel = new CostumerRegister();
    rModel.AllStores = getStoresForUser(User.Identity.GetUserId());
    //to auto select the first element of the select list
    rModel.AllStores.First().Selected = true;
    return View(rModel);
}

public SelectList getStoresForUser(string userId){
//...
}

On my View:

@Html.ListBoxFor(m => m.SelectedStores, Model.AllStores, new { @class = "form-control" })

I would expect to have the first element selected on the view but it appears not selected.

1 Answers

1
hassan.ef On

use this one I think its useful:

public ActionResult Index()
        {
            // Preselect items with id 1 and 3
            var selectedItemIds = new[] { 1, 3 };

            var model = new MyViewModel
            {
                Items = new MultiSelectList(
                    new[] 
                    {
                        // TODO: Fetch from your repository
                        new { Id = 1, Name = "item 1" },
                        new { Id = 2, Name = "item 2" },
                        new { Id = 3, Name = "item 3" },
                    }, 
                    "Id", 
                    "Name", 
                    selectedItemIds
                )
            };

            return View(model);
        }