Luis Valencia
Luis Valencia

Reputation: 33978

How to bind a list of comma separated values to a Listbox

In my asp.net mvc app I have a create view where I need to select a list of companies, so I have this:

@{
   var unitOfWork = new UnitOfWork();
   var empresas = unitOfWork.EmpresaRepository.Get();
 }
   <div class="form-group">
    @Html.Label("Empresa", new { @class = "control-label col-md-2" })

    <div class="col-md-10">
     @Html.ListBox("Empresa", new SelectList(empresas, "Id", "Nombre"), new { @class = "form-control" })
    </div>
   </div>

Basically I select all companies from my repository and then I render them on a list box, when I hit Save the selected companies are saved as a comma separated list of IDS, check formcollection

 //Setting extended property lookup name
 var extPropLookupName = $"extension_{SettingsHelper.ClientId.Replace("-", "")}_{"Compania"}";

 //TO BE FINISHED
 user.SetExtendedProperty(extPropLookupName, formCollection["Empresa"]);
 await user.UpdateAsync();

Now I am trying to implement the EDIT view. so I know how to get the comma separated list, I also know how to get the list of companies, but the ListBox should show which are the SELECTED companies.

@{
   var unitOfWork = new UnitOfWork();
   var empresas = unitOfWork.EmpresaRepository.Get();
   var keyvaluepair = Model.GetExtendedProperties().Where(prop => prop.Key == extPropLookupName).FirstOrDefault();
   if (keyvaluepair.Value != null)
   {
   <div class="form-group">
   @Html.Label("Empresa", new { @class = "control-label col-md-2" })

     <div class="col-md-10">
      @Html.ListBox("Empresa", new SelectList(empresas, "Id", "Nombre"),  new { @class = "form-control" })
     </div>
   </div>
   }
}

Right now it renders the list of companies but with none selected, I know keyvaluepair.Value will have "1,2,3".

How can I bind that to the listbox so that it renders the selected items?

Upvotes: 1

Views: 1511

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239240

The backing makes no difference, you can still utilize a view model to work with the data in a strongly typed way. Just create a class that has properties to represent what you want to work with in AD, and then map your AD values to/from this class.

Then, you can do something like the following:

public class UserViewModel
{
    ...

    public List<string> SelectedCompanies { get; set; }
}

In your action:

var model = new UserViewModel
{
    ...

    SelectedCompanies = user.GetExtendedProperty(extPropLookupName).Split(',')
}

And after post:

user.SetExtendedProperty(extPropLookupName, string.Join(",", model.SelectedCompanies);

Then, in your view:

@Html.ListBoxFor(m => m.SelectedCompanies, new SelectList(empresas, "Id", "Nombre"),  new { @class = "form-control" })

Upvotes: 2

Related Questions