Rei*_*aka 4 asp.net asp.net-mvc
可能不是一个非常重要的问题,但......
我有一堆主要是静态的页面:联系人,关于,使用条款,以及大约7-8个.
应该是每个都有自己的控制器,还是我应该只为每个控制器执行一个操作?
提前致谢.
将静态页面添加到mvc应用程序的最佳方法是创建一个名为Pages(或任何你想要的)的单独控制器,并将页面名称Index作为参数传递给它们的方法.因此,您需要在渲染之前测试页面是否存在,如果存在则渲染它,否则渲染您的自定义Page Not Found页面.这是一个例子:
在Global.asax中:
// put the StaticPage Rout Above the Default One
routes.MapRoute(
"StaticPages",
"Pages/{page}",
new { controller = "Pages", action = "Index"}
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional}
);
Run Code Online (Sandbox Code Playgroud)
创建一个名为PagesController的Controller:
public class PagesController : Controller
{
public ActionResult Index(string page)
{
// if no paramere was passed call the default page
if (string.IsNullOrEmpty(page)) {
page = "MyDefaultView";
}
// Check if the view exist, if not render the NotfoundView
if (!ViewExists(page)) {
page = "PageNotFoundView";
}
return View(page);
}
// function that check if view exist
private bool ViewExists(string name)
{
ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null);
return (result.View != null);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2195 次 |
| 最近记录: |