Tool:Visual Studio 2013 Ultimate Update 3
OS:Windows 8.1
ASP.NET MVC 5
ASP.NET MVC5支援Attribute Routing的功能,可參考<ASP.NET MVC5 Attribute Routing簡介>一文。若要在MVC專案中快速產生支援AttributeRouting的控制器,可以利用現成的ScaffolderTemplates。
參考以下步驟:
- 建立Empty- MVC 專案
- 使用NuGet下載套件:
專案中將會加入許多範本:
- 修改RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes( );
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
- 加一個HomeController
- 新增Controller
- 產生的code已有設定Attribute Routing
namespace WebApplication1.Controllers
{
[RoutePrefix("Home")]
[Route("{action}/{id}")]
public class HomeController : Controller
{
// GET: Home
[Route]
public ActionResult Index()
{
return View();
}
// GET: Home/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Home/Create
[Route("Create")]
public ActionResult Create()
{
return View();
}
// POST: Home/Create
[HttpPost]
[Route("Create")]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Home/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Home/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Home/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Home/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
- 加個Index View
- Index View加上標題
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<h1>Home</h1>
</div>
</body>
</html>
- 執行測試,顯示Index View,這表示路由已正確運作。
沒有留言:
張貼留言