2010-03-25 150 views
1

考慮控制器CustomerController.cs上兩種方法:ASP.NET MVC:路由幫助

//URL to be http://mysite/Customer/ 
public ActionResult Index() 
{ 
    return View("ListCustomers"); 
} 

//URL to be http://mysite/Customer/8 
public ActionResult View(int id) 
{ 
    return View("ViewCustomer"); 
} 
  • 你如何設置你的路由,以適應這一要求?
  • 如何在創建指向View頁面的鏈接時使用Html.ActionLink?

回答

1

在的global.asax.cs,加以下(假設你使用默認的MVC的Visual Studio模板)

Route.MapRoute("Customer", 
    "Customer/{id}", 
    new { Controller = "CustomerController", action="View", id="" }); 

確保你把該路由的默認路由之前在模板

然後你需要修改你的控制器。查看,

public ActionResult View(int? id) 
{ 
    if (id == null) 
    { 
     return RedirectToAction("Index"); // So that it will list all the customer 
    } 
    //...The rest follows 
} 

對於第二個問題,ActionLink很簡單。

Html.ActionLink("Link Text", "View", "Customer", new {id=1}, null);