列表框在MVC 2 [英] LIstbox in MVC 2
本文介绍了列表框在MVC 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Employee表。从我要加载的员工姓名列表框中。我不从那里我应该开始知道。请指引我。
I am having a Employee Table. From that i want to load the Employee Names in a List Box. I dont know from where i should start. Kindly guide me.
推荐答案
像往常一样通过定义将重新present您的数据视图模型启动:
As always start by defining the view model that will represent your data:
public class Employee
{
public string Id { get; set; }
public string Name { get; set; }
}
public class MyViewModel
{
public string SelectedEmployeeId { get; set; }
public IEnumerable<Employee> Employees { get; set; }
}
然后,控制器将操作模式:
Then the controller which will manipulate the model:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// TODO: Instead of hardcoding fetch from your repository
Employees = Enumerable.Range(1, 5).Select(i => new Employee
{
Id = i.ToString(),
Name = "employee " + i
})
};
return View(model);
}
}
最后生成视图中的下拉列表:
And finally generate a dropdown list in the view:
<%: Html.DropDownListFor(
x => x.SelectedEmployeeId,
new SelectList(Model.Employees, "Id", "Name")
) %>
如果你想允许多重选择列表框a.k.a一些改变是必要的。首先,你需要员工ID阵列在你的模型:
If you want to allow multiple selections a.k.a ListBox a few changes are necessary. First you need an array of employee ids in your model:
public class MyViewModel
{
public string[] SelectedEmployeeIds { get; set; }
public IEnumerable<Employee> Employees { get; set; }
}
然后用在视图中的 ListBoxFor
助手:
<%: Html.ListBoxFor(
x => x.SelectedEmployeeIds,
new SelectList(Model.Employees, "Id", "Name")
) %>
这篇关于列表框在MVC 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文