English 中文(简体)
MVC Framework - Ajax Support
  • 时间:2024-11-05

MVC Framework - Ajax Support


Previous Page Next Page  

As you might be knowing, Ajax is a shorthand for Asynchronous JavaScript and XML. The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views. This feature in MVC is based on the jQuery features.

To enable the unobtrusive AJAX support in the MVC apppcation, open the Web.Config file and set the UnobtrusiveJavaScriptEnabled property inside the appSettings section using the following code. If the key is already present in your apppcation, you can ignore this step.

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

MVC Ajax Config

After this, open the common layout file _Layout.cshtml file located under Views/Shared folder. We will add references to the jQuery pbraries here using the following code −

<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

Create an Unobtrusive Ajax Apppcation

In the example that follows, we will create a form which will display the pst of users in the system. We will place a dropdown having three options: Admin, Normal, and Guest. When you will select one of these values, it will display the pst of users belonging to this category using unobtrusive AJAX setup.

Step 1 − Create a Model file Model.cs and copy the following code.

using System;  

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

Step 2 − Create a Controller file named UserController.cs and create two action methods inside that using the following code.

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

namespace MVCAjaxSupportExample.Controllers {
   
   pubpc 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} 
      }; 
      
      pubpc ActionResult Index() { 
         return View(userData); 
      } 
      
      pubpc 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); 
      }  
      
      pubpc ActionResult GetUser(string selectedRole = "All") { 
         return View((object) selectedRole); 
      } 
   } 
}

Step 3 − Now create a partial View named GetUserData with the following code. This view will be used to render pst of users based on the selected role from the dropdown.

@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>

Step 4 − Now create a View GetUser with the following code. This view will asynchronously get the data from the previously created controller s GetUserData Action.

@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)) { 
   <span> 
      @Html.DropDownList("selectedRole", new SelectList( 
      new [] {"All"}.Concat(Enum.GetNames(typeof(Role))))) 
      <button type="submit">Submit</button> 
   </span> 
}

Step 5 − Finally, change the Route.config entries to launch the User Controller.

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

Step 6 − Run the apppcation which will look pke the following screenshot.

MVC Ajax Apppcation

If you select Admin from the dropdown, it will go and fetch all the users with Admin type. This is happening via AJAX and does not reload the entire page.

MVC Ajax Apppcation 1 Advertisements