ASP.NET MVC Content Path (相對 & 絕對路徑)


  1. 說明
    1. Url.Action
    2. Url.Content
  2. 相關連結

筆記 ASP.NET 開發時,如何處理相對路徑資源使用的相關問題,包含 Url.ActionUrl.Content 的介紹。

logo

說明

Url.Action

Url.Action 可以用於處理 js script 需要組合 API 呼叫的使用。

$.ajax({
   url: '@Url.Action("Products", "API")'
})

Url.Content

使用 Url.Content 可以將 相對路徑 轉換為 絕對路徑,例如想要在 Razor cshtml 的 scripts 部分載入其他 js 資源時使用。

這邊的 相對路徑 是專指使用 波浪號(Tilde) 的 Virtual Path 轉換,而非使用上一層點號的轉換 (例如 ../ 或者 ../../)。

Vue.cshtml

<script src='@Url.Content("~/Scripts/Library/index.js")'></script>

使用 Url.Content 的時候,不會有 intellisence,所以使用起來會稍微有點不安感,但可以在在 Html 部分先使用 script:src 的方式先輸入好 Virtual Path 再加入到 Scripts 的部分。

需要注意的是如果 js script 是獨立的 js 檔案,則沒有辦法使用 Url.Cotent,因為 Razor 不會作用在 js 檔上。如果需要將 js 獨立成專門的檔案,替代的方案是將 js Scripts 獨立為 cshtml,如此一來便可以使用 Url.Content,如果要引入的話則使用 @Html.Partial 引入 🤩

Vue.cshtml

相關連結

ASP.NET MVC 從無到有打造一個應用系統

Visual Studio 入門教學