如何在 MVC4 中使用 Html.ListBoxFor

Dav*_*het 5 c# asp.net-mvc-4

我正在尝试填充一个列表框。我的模型只是一个列表。我找不到我需要与@Html.ListBoxFor() 一起使用的参数的简单解释。

这是我的代码的一部分:

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

    return View(names);
}

...
Run Code Online (Sandbox Code Playgroud)

在视图中:

@model List<string>

...

@Html.ListBoxFor(?)
Run Code Online (Sandbox Code Playgroud)

谢谢。

Zee*_*han 8

您可以在控制器操作中将模型列表填充为:

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;
}
Run Code Online (Sandbox Code Playgroud)

在您的 .cshtml 中,您可以将其用作:

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

为了处理视图中的列表,您需要将其转换为SelectList类型。在我们的示例中,假设Country是用于此目的的模型。(具有选择列表的键和值)