首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET MVC 路由擴展:連結與 URL 生成機制

     編輯:關於ASP.NET

ASP.NET 路由系統不僅處理輸入請求的路由解析,也支援根據註冊路由規則生成輸出 URL。前者依賴 RouteCollection.GetRouteData,後者則透過 GetVirtualPathData 實現。為了方便開發,ASP.NET MVC 提供了 HtmlHelper 與 UrlHelper 兩大輔助類別,分別用於生成超連結(ActionLink/RouteLink)與純 URL(Action/RouteUrl),底層皆呼叫 GetVirtualPathData。

UrlHelper 與 HtmlHelper 核心定義

UrlHelper 封裝 RequestContext 與 RouteCollection:

public class UrlHelper
{
    public UrlHelper(RequestContext requestContext);
    public UrlHelper(RequestContext requestContext, RouteCollection routeCollection);
    public RequestContext RequestContext { get; }
    public RouteCollection RouteCollection { get; }
}

HtmlHelper 則透過 ViewContext 取得請求上下文與路由資料:

public class HtmlHelper
{
    public HtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer);
    public HtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection);
    public RouteCollection RouteCollection { get; }
    public ViewContext ViewContext { get; }
}

Action 連結與 URL 生成

UrlHelper.Action 多載支援指定 Action、Controller、路由值、協定與主機名,若指定協定則回傳完整 URL,否則為相對 URL。HtmlHelper.ActionLink 則生成完整的 <a> 標籤,其目標 URL 生成邏輯與 UrlHelper 一致。

public static class LinkExtensions
{
    public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName);
    public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);
    // ... 其他多載
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved