Question

I am trying to populate a ListBox. My model is just a List. I cannot find a simple explanation of parameters that I would need to use with @Html.ListBoxFor().

Here is a part of my code:

public ActionResult Index()
{
     List<string> names = GetAllNames();

    return View(names);
}

...

In the view:

@model List<string>

...

@Html.ListBoxFor(?)

Thanks.

Was it helpful?

Solution

you can populate you Model list in you controller action as:

someAction
{
    CountryModel objcountrymodel = new CountryModel();  
    objcountrymodel.CountryList = GetAllCountryList();
    return View(objcountrymodel);
}

public SelectList GetAllCountryList()
{
    List<Country> objcountry = new List<Country>();
    objcountry.Add(new Country { Id = 1, CountryName = "India" });
    objcountry.Add(new Country { Id = 2, CountryName = "USA" });
    objcountry.Add(new Country { Id = 3, CountryName = "Pakistan" });
    objcountry.Add(new Country { Id = 4, CountryName = "Nepal" });
    SelectList objselectlist = new SelectList(objcountry, "Id", "CountryName");
    return objselectlist;
}

and in your .cshtml, you may use it as:

@Html.ListBoxFor(m => m.SelectedCountry, new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue), new { @Id = "lstcountry", @style = "width:200px;height:60px;" })

for dealing with lists in view, you need to cast it to SelectList type. and in our example, Country is assumed to be a model for that purpose. (having key and value for selectlist)

OTHER TIPS

First you need to create a viewModel; here we suppose it's named ListBoxViewModel.

public class ListBoxtViewModel
{
   public string SelectedItem{get;set;}
   public List<SelectListItem> selectItemList{get;set;)
}

Second, add using below code to your view.

@Html.ListBoxFor(m=>m.SelectedItem, List<SelectListItem> selectItemList)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top