Listbox Binding from the Backend MVC2
Here, the listbox is loaded sample Text. My Model.aspx will be
public class Employee
{
public string Id { get; set; }
public string Name { get; set; }
}
public class MyViewModel
{
public开发者_JS百科 string[] SelectedEmployeeIds { get; set; }
public IEnumerable<Employee> Employees { get; set; }
}
HomeController.cs
public ActionResult About()
{
var model = new MyViewModel
{
Employees = Enumerable.Range(1, 5).Select(i => new Employee
{
Id = i.ToString(),
Name = "employee " + i
})
};
return View(model);
}
About.aspx
<%: Html.ListBoxFor(
x => x.SelectedEmployeeIds,
new SelectList(Model.Employees, "Id", "Name")
) %>
The above code is working fine. I want to load the list box from the Backend (i.e Emp Table)...Where should i do that.
You didn't provide any information about this Emp Table
. The proper way to perform this in ASP.NET MVC is to abstract the data access into a repository and use this repository from your controller:
public interface IEmployeesRepository
{
IEnumerable<Employee> GetEmployees();
}
And now your controller becomes:
public class HomeController: Controller
{
private readonly IEmployeesRepository _repository;
public HomeController(IEmployeesRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
var model = new MyViewModel
{
Employees = _repository.GetEmployees()
};
return View(model);
}
}
As you can see the data access is abstracted away from the controller and it doesn't really care about where are those employees coming from. It is at this moment that this stops to be an ASP.NET MVC related question and becomes a question about how to implement this interface using some data access technology.
Let's suppose that you were using Linq to Entities as ORM. Your implementation could look like this:
public class EmployeesRepositorySql: IEmployeesRepository
{
public IEnumerable<Employee> GetEmployees()
{
using (var db = new EmployeesDbContext())
{
return db.Employees;
}
}
}
OK, so as you can see we have introduced the data context class which is automatically generated by Visual Studio when you add a new entity from an existing database. If you are not familiar with the Entity Framework you could read some getting started tutorials.
or if you prefer to use ADO.NET directly:
public class EmployeesRepositorySql: IEmployeesRepository
{
public IEnumerable<Employee> GetEmployees()
{
using (var conn = new SqlConnection("SOME CONNECTION STRING"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Id, Name FROM Employees;";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new Employee
{
Id = reader.GetString(0),
Name = reader.GetString(1)
};
}
}
}
}
}
The last part that is left is to instruct our controller to use this particular implementation of the repository. This could be achieved with a DI framework. Here's an article explaining this.
精彩评论