Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Html.ListBoxFor with MVC4

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.

like image 544
David Shochet Avatar asked May 13 '14 11:05

David Shochet


Video Answer


2 Answers

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)

like image 95
Zeeshan Avatar answered Oct 15 '22 17:10

Zeeshan


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)
like image 32
Paul Cong Avatar answered Oct 15 '22 16:10

Paul Cong