Reputation: 10723
I'm making an Asp.Net MVC 3 project which should have about 10-15 views.
How should I decide if I should put them in one controller or many controllers?
Or is it a better approach to use one controller for one table of the database?
Upvotes: 0
Views: 77
Reputation: 218852
You can create controllers based on your domain needs. For example if you have a system which has a signup form /login , you can create a controller for that with name "User" and can have different Actions methods for these.
public class UsersController : Controller
{
// Get Request
public ActionResult Signup()
{
return View();
}
// Sign up post
[HttpPost]
public ActionResult Signup()
{
// to do : your signup validation logic here
return View();
}
// Get Request
public ActionResult Login()
{
return View();
}
// Login post
[HttpPost]
public ActionResult Login()
{
return View();
}
}
similarly you can have another controller for your another domain model like Product
public class ProductsController : Controller
{
// Get Request to list all Products
public ActionResult List()
{
return View();
}
//remaining action methods based on your need
}
I guess, your tables will be mostly represnting your domain model. so you can create a controller for each table like User, Customer, Products,Order etc..
Upvotes: 0
Reputation: 2229
Definitely not better to use a controller to table approach unless your tables are laid out such that each logical object and all of its pieces are in one table. As Dismissle said. Logical groupings either by module or user group or permissions or a combination. i.e. Registration, login, products, usersadmin and so on.
Upvotes: 0
Reputation: 7514
Typically you should create a new Controller anytime you encounter a new Business Entity that for which you do not have a Controller already. Therefore, you may create a CustomerController
and a ProductsController
, but it doesn't make sense to create a CustomersToProductsController
.
Controllers are neither 1-to-1 with database tables and they are certainly not 1-to-1 with Views. I hope this helps.
Upvotes: 0
Reputation: 13409
Depends on your design really. Example: Client with address, might be saved in multiple tables (clientinfo, address, etc.), you probably are better off with just a client controller in that case. Anyways, it's just one scenario.
Upvotes: 0
Reputation: 33071
Separate your controllers logically. If you have something that is dealing with Products, make a Products controller. If you are dealing with an Account, use an AccountsController, etc.
Upvotes: 3