新建一个空的MVC项目,目录结构如下:
在Controllers,Models,Views三个文件夹中建立对应的MVC。
如上图,右键Controllers文件夹新建一控制器,注意必须以Controller结尾,这是ASP.NET MVC的约定。生成LoginControler.cs文件,代码如下:
public ActionResult Login()
{
return View();
}
在方法体内右键,选择添加视图:
在View文件夹下生成一Login.cshtml文件。
Login.cshtml文件代码如下:
<body>
<div>
first asp.net mvc
</div>
</body>
在WebForm中我们通过起始页设置启动的默认页,在ASP.NET MVC中通过配置App_Start文件夹下的RouteConfig.cs设置启动的默认页。
RouteConfig.cs文件代码如下:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
//defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
defaults: new { controller = "Login", action = "Login", id = UrlParameter.Optional }
);
}
运行项目结果如下:
添加多一个路由,发现多个路由时,第一个起效:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/{id}",
//defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
defaults: new { controller = "Login", action = "Login2", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
//defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
defaults: new { controller = "Login", action = "Login", id = UrlParameter.Optional }
);
}