§8.3.1 Generating Hyperlinks with Html.ActionLink()
最簡單的產生url的方式就是從一個視圖模板調用Html.ActionLink().比如:
<%: Html.ActionLink("See all of our products", "List", "Products") %>
它的實現效果如下
<a href="/Products/List">See all of our products</a>
注意, 這裡如果你沒有指定controller, 他會預設你當前的controller
Passing Extra Parameters
你可以傳遞額外的route入口需要的參數.
<%: Html.ActionLink("Red items", "List", "Products",new { color="Red", page=2 }, null) %>
它的實現效果:
<a href="/Products/List?color=Red&page=2">Red items</a>
如果,你的route配置中有這樣的配置方式Products/List/{color}/{page},那麼就會產生如下的代碼
<a href="/Products/List/Red/2">Red items</a>
How Parameter Defaults Are Handled
當我們寫下下面的代碼的時候, 而且product的預設action是index
<%: Html.ActionLink("Products homepage", "Index", "Products") %>
它的實現效果如下
<a href="/Products">Products homepage</a>
這裡因為預設情況下相同, 所以省略了index
Generating Fully Qualified Absolute URLs
Html.ActionLink() 通常產生的是URL的一部分,(i.e. /Products,而不是http://www.example.com/Products). 如果你想產生一個完整的URL, 如下:
<%: Html.ActionLink("Click me", "MyAction", "MyController", "https","www.example.com", "anchorName", new { param = "value" },new { myattribute = "something" }) %>
它的效果如下:
<a myattribute="something" href="https://www.example.com/MyController/MyAction?param=value#anchorName">Click me</a>
§8.3.2 Generating Links and URLs from Pure Routing Data
Html.RouteLink() 和 Html.ActionLink() 是類似的.
<%: Html.RouteLink("Click me", new { controller = "Products", action = "List" }) %>
它會產生如下的連結
<a href="/Products/List">Click me</a>
同樣的,Url.RouteUrl() 和Url.Action() 是類似的 .
<%: Url.RouteUrl(new { controller = "Products", action = "List" }) %>
產生如下的URL: /Products/List
在mvc應用程式中, 這些是不常用的, 但是熟悉他們還是有好處的.
§8.3.3 Performing Redirections to Generated URLs
實現一個重新導向功能, 只要簡單的返回RedirectToAction()結果, 並且傳入目標controller和action方法.
public ActionResult MyActionMethod(){return RedirectToAction("List", "Products");}
如果你想擷取一個URL字串, 而不是實現HTTP重新導向, 你可以做如下:
public ActionResult MyActionMethod(){string url = Url.Action("SomeAction", new { customerId = 456 });// ... now do something with url}
§8.3.4 Understanding the Outbound URL-Matching Algorithm
§8.3.5 Generating Hyperlinks with Html.ActionLink<T> and Lambda Expressions
§8.3.6 Working with Named Routes