How to use Html.ListBoxFor with MVC4

asp.net-mvc-4, c#

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)

Problem

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.

Original source