以前在開發 ASP.NET MVC 4 的時候,Visual Studio 的專案範本中本身就已經包含了 Microsoft jQuery Unobtrusive Ajax 這個 NuGet 套件,所以當你想用 @Ajax 輔助方法時,自然不會遇到什麼困難。打從 ASP.NET MVC 5 開始,Visual Studio 2013 的專案範本改成預設不安裝 Microsoft jQuery Unobtrusive Ajax 套件,想用的時候不是安裝一下就好嗎?我自己一直這樣認為,所以不覺得有什麼不對,不過前陣子還是有同事剛從 ASP.NET MVC 4 升級到 ASP.NET MVC 5,他在第一次開發 ASP.NET MVC 5 專案時剛好也有用到 @Ajax 輔助方法,還是被卡關了一些時間,因此特別撰文提醒這個問題。
如果要安裝這個套件,可參考以下步驟圖示:


也可以直接在套件管理器主控台輸入以下指令:
PM> Install-Package Microsoft.jQuery.Unobtrusive.Ajax

安裝成功後,請記得要將 jquery.unobtrusive-ajax.js 或 jquery.unobtrusive-ajax.min.js 檔案載入到頁面中,且要載入在 jQuery 函式庫之後,這樣才可以讓 @Ajax 正常運作。

以下是 App_Start\BundleConfig.cs 這隻程式的程式碼範例:
bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
"~/Scripts/jquery.unobtrusive-ajax*"));

以下是將 Bundle 過的網址加入到頁面中的語法範例:
@Scripts.Render("~/bundles/jqueryajax")

相關連結