Hey there, I'm trying to make a site which have following: News, Products, About and Contact. The problem is that for example the Products - I have an Index view to list the products for the user, but what if I want to make a "control panel" where I should be able to edit the products(names, prices, quantity) - how should that be done without have to create double productController?
1 Answer
You can have different views associated to one controller. Each view will be linked to an action method in your controller.
You could, for exemple, define your ProductController class like this
public class ProductController : Controller {
[HttpGet]
public ActionResult Index() {
var productList = ProductService.GetProducts();
return View( productList );
}
[HttpGet]
public ActionResult Edit( int id ) {
var product = ProductService.GetProduct( id );
return View( product );
}
[HttpPost]
public ActionResult Edit( ProductModel product ) {
if (ModelState.IsValid()) {
// save the changes
return RedirectToAction( "Index" );
}
return View( product );
}
}
And have the corresponding views in your Views folder :
Views
| -- Product
| -- Index.aspx
| -- Edit.aspx
5 Comments
ebb
Ah, must have been me there havent explained correctly. What I'm trying to is making a small CMS. You navigate to something.com/products and see the products listed. If you then go to panel.something.com and login you have a site where you can manage all of the pages for example the products. My question is should the panel and the normal site share controllers?
Mike
You would normally have different CRUD actions in the one controller. For the Create / Update / Delete actions, you just need to mark the action in the controller with the [Authorize] attribute to make sure a user is authorised to perform that action. asp.net/mvc/tutorials/….
ebb
Yes, I'm aware of that Michael. The problem is that on panel.something.com/products - I want to be able to list the products once again but this time with Edit/Delete links. Should I create a new view for list in my panel or can I reuse the view that I have used for something.com/products ?
Bertrand Marron
They seem to be different applications. You could go for the Area approach, create a
Panel area and use the same services.ebb
My bad Bertrand, your first solution was perfect! - Thanks.