LIstbox in MVC 2

徘徊边缘 提交于 2019-12-11 07:21:16

问题


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.


回答1:


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")
) %>

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; }
}

And then use the ListBoxFor helper in the view:

<%: Html.ListBoxFor(
    x => x.SelectedEmployeeIds,
    new SelectList(Model.Employees, "Id", "Name")
) %>



回答2:


you could also try my AjaxDropdown helper and populate your listbox via jquery Ajax (you don't have to know anything about jquery)

http://awesome.codeplex.com/

there is a live demo that you can try and download



来源:https://stackoverflow.com/questions/4203800/listbox-in-mvc-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!