asp.net-mvc 单个控制器的 MVC 多个视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4866455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC multiple views for a single controller
提问by zach attack
Is it possible in MVC to do the following with a single controller "ListController" to take care of the following pages...
是否可以在 MVC 中使用单个控制器“ListController”执行以下操作来处理以下页面...
www.example.com/List/Cars/ForSale/{id} optional
www.example.com/List/Cars/ForRent/{id} optional
www.example.com/List/Search/
www.example.com/List/Boats/ForSale/{id} optional
www.example.com/List/Boats/ForRent/{id} optional
www.example.com/List/Boats/Search/
www.example.com/List/Cars/ForSale/{id} 可选
www.example.com/List/Cars/ForRent/{id} 可选
www.example.com/List/Search/
www.example.com/List/Boats/ForSale/{id} 可选
www.example.com/List/Boats/ForRent/{id} 可选
www.example.com/List/Boats/Search/
If not, is there any way to get around it besides making a CarsController and BoatsController separate? They will be using the same logic just would like the URLs different.
如果没有,除了将 CarsController 和 BoatsController 分开之外,还有什么办法可以绕过它?他们将使用相同的逻辑,只是希望 URL 不同。
回答by Matthew Manela
You can definitely do this. It is simple using routing. You can route the different urls to different actions in your controller.
你绝对可以做到这一点。使用路由很简单。您可以将不同的 url 路由到控制器中的不同操作。
Here are examples of defining some of the above urls:
以下是定义上述某些 url 的示例:
routes.MapRoute("CarSale"
"/List/Cars/ForSale/{id}",
new { controller = "list", action = "carsale", id = UrlParameter.Optional } );
routes.MapRoute("ListSearch"
"/List/search",
new { controller = "list", action = "search"} );
routes.MapRoute("BoatSale"
"/List/Boats/ForSale/{id}",
new { controller = "list", action = "boatsale", id = UrlParameter.Optional } );
Then in your controller you would have action methods for each:
然后在您的控制器中,您将拥有每个操作方法:
public ListController
{
// ... other stuff
public ActionResult CarSale(int? id)
{
// do stuff
return View("CarView");
}
public ActionResult BoatSale(int? id)
{
// do stuff
return View("BoatView");
}
// ... other stuff
}
回答by bhavsar japan
Yes You can use multiple Viewin one Controller.
是的,您可以在一个控制器中使用多个视图。
Let's take one Example, I have one ControllerCalled Lawyers
让我们举一个例子,我有一个叫律师的控制员
public class LawyersController : Controller
{
// GET: Lawyers
public ActionResult Login()
{
return View();
}
public ActionResult Signup()
{
return View();
}
so I have one controller and 2 views.
所以我有一个控制器和 2 个视图。