开发者

LIstbox in MVC 2

开发者 https://www.devze.com 2023-01-26 01:28 出处:网络
I am having a Employee Table. From that i want to load the Employee Nam开发者_开发知识库es in a List Box. I dont know from where i should start. Kindly guide me.As always start by defining the view mo

I am having a Employee Table. From that i want to load the Employee Nam开发者_开发知识库es in a List Box. I dont know from where i should start. Kindly guide me.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消