MVC 框架 - Ajax 支援



如您所知,Ajax 是非同步 JavaScript 和 XML 的縮寫。MVC 框架內建了對非侵入式 Ajax 的支援。您可以使用輔助方法定義您的 Ajax 功能,而無需在所有檢視中新增程式碼。MVC 中此功能基於 jQuery 功能。

要在 MVC 應用程式中啟用非侵入式 AJAX 支援,請開啟 Web.Config 檔案,並在 appSettings 部分使用以下程式碼設定 UnobtrusiveJavaScriptEnabled 屬性。如果您的應用程式中已存在此鍵,則可以忽略此步驟。

<add key = "UnobtrusiveJavaScriptEnabled" value = "true" />

MVC Ajax Config

之後,開啟位於 Views/Shared 資料夾下的通用佈局檔案_Layout.cshtml檔案。我們將在此處使用以下程式碼新增對 jQuery 庫的引用 -

<script src = "~/Scripts/jquery-ui-1.8.24.min.js" type = "text/javascript">
</script> 

<script src = "~/Scripts/jquery.unobtrusive-ajax.min.js" type = "text/javascript">
</script>
MVC Ajax Config 1

建立非侵入式 Ajax 應用程式

在下面的示例中,我們將建立一個表單,該表單將顯示系統中使用者的列表。我們將放置一個下拉列表,其中包含三個選項:管理員、普通使用者和訪客。當您選擇其中一個值時,它將使用非侵入式 AJAX 設定顯示屬於此類別的使用者列表。

步驟 1 - 建立模型檔案 Model.cs 並複製以下程式碼。

using System;  

namespace MVCAjaxSupportExample.Models { 
   
   public class User { 
      public int UserId { get; set; } 
      public string FirstName { get; set; } 
      public string LastName { get; set; } 
      public DateTime BirthDate { get; set; } 
      public Role Role { get; set; } 
   }  
   
   public enum Role { 
      Admin, 
      Normal, 
      Guest 
   } 
}  

步驟 2 - 建立一個名為 UserController.cs 的控制器檔案,並在其中使用以下程式碼建立兩個操作方法。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Mvc; 
using MVCAjaxSupportExample.Models;  

namespace MVCAjaxSupportExample.Controllers {
   
   public class UserController : Controller { 
      
      private readonly User[] userData = 
      { 
         new User {FirstName = "Edy", LastName = "Clooney", Role = Role.Admin}, 
         new User {FirstName = "David", LastName = "Sanderson", Role = Role.Admin}, 
         new User {FirstName = "Pandy", LastName = "Griffyth", Role = Role.Normal}, 
         new User {FirstName = "Joe", LastName = "Gubbins", Role = Role.Normal}, 
         new User {FirstName = "Mike", LastName = "Smith", Role = Role.Guest} 
      }; 
      
      public ActionResult Index() { 
         return View(userData); 
      } 
      
      public PartialViewResult GetUserData(string selectedRole = "All") { 
         IEnumerable data = userData; 
         
         if (selectedRole != "All") { 
            var selected = (Role) Enum.Parse(typeof (Role), selectedRole); 
            data = userData.Where(p => p.Role == selected); 
         } 
         
         return PartialView(data); 
      }  
      
      public ActionResult GetUser(string selectedRole = "All") { 
         return View((object) selectedRole); 
      } 
   } 
}

步驟 3 - 現在建立一個名為 GetUserData 的部分檢視,並使用以下程式碼。此檢視將用於根據從下拉列表中選擇的角色呈現使用者列表。

@model IEnumerable<MVCAjaxSupportExample.Models.User> 

<table> 
   <tr> 
      <th> 
         @Html.DisplayNameFor(model => model.FirstName) 
      </th> 
      
      <th> 
         @Html.DisplayNameFor(model => model.LastName) 
      </th> 
      
      <th> 
         @Html.DisplayNameFor(model => model.BirthDate) 
      </th> 
      <th></th> 
   </tr>  

   @foreach (var item in Model) { 
   <tr> 
      <td> 
         @Html.DisplayFor(modelItem => item.FirstName) 
      </td> 
      
      <td> 
         @Html.DisplayFor(modelItem => item.LastName) 
      </td> 
      
      <td> 
         @Html.DisplayFor(modelItem => item.BirthDate) 
      </td> 
      
      <td> 
         
      </td> 
   </tr> 
}  
</table>

步驟 4 - 現在建立一個名為 GetUser 的檢視,並使用以下程式碼。此檢視將非同步獲取來自先前建立的控制器的 GetUserData 操作的資料。

@using MVCAjaxSupportExample.Models 
@model string 

@{ 
ViewBag.Title = "GetUser"; 

AjaxOptions ajaxOpts = new AjaxOptions { 
UpdateTargetId = "tableBody" 
}; 
} 

<h2>Get User</h2> 
<table> 
   <thead>
      <tr>
         <th>First</th>
         <th>Last</th>
         <th>Role</th>
      </tr>
   </thead> 
   
   <tbody id="tableBody"> 
      @Html.Action("GetUserData", new {selectedRole = Model }) 
   </tbody> 
</table>  

@using (Ajax.BeginForm("GetUser", ajaxOpts)) { 
   <div> 
      @Html.DropDownList("selectedRole", new SelectList( 
      new [] {"All"}.Concat(Enum.GetNames(typeof(Role))))) 
      <button type="submit">Submit</button> 
   </div> 
}

步驟 5 - 最後,更改 Route.config 條目以啟動使用者控制器。

defaults: new { controller = "User", action = "GetUser", id = UrlParameter.Optional }

步驟 6 - 執行應用程式,它將如下面的螢幕截圖所示。

MVC Ajax Application

如果您從下拉列表中選擇管理員,它將獲取所有型別為管理員的使用者。這是透過 AJAX 完成的,並且不會重新載入整個頁面。

MVC Ajax Application 1
廣告