2010-03-25 156 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);