Method for JQuery to load PartialView asynchronously

  • 2021-06-28 08:17:16
  • OfStack

This article provides an example of how JQuery loads PartialView asynchronously.Share it for your reference, as follows:

Requirements: There are controls like dropdown on the page, and when different values are selected, the content associated below changes.

Idea: Put the changing content associated with dropdown into PartialView (ascx), bind dropdown's change event with JQuery, request Action related to PartialView with JQuery ajax when the selected value changes, and get the data to cover the original content.

Realization:

Model class:


public class User
{
    public string UserName { get; set; }
    public int Age { get; set; }
    public int UserID { get; set; }
    public static List<User> GetUsers()
    {
      List<User> userList = new List<User>();
      User user = null;
      user = new User();
      user.UserID = 1;
      user.UserName = " Xiao Ming ";
      user.Age = 20;
      userList.Add(user);
      user = new User();
      user.UserID = 2;
      user.UserName = " Little Red ";
      user.Age = 21;
      userList.Add(user);
      user = new User();
      user.UserID = 3;
      user.UserName = " Cockroach ";
      user.Age = 22;
      userList.Add(user);
      return userList;
    }
    public static User GetUserById(int userId)
    {
      return GetUsers().SingleOrDefault(u=>u.UserID==userId);
    }
}

Our PartialView:


<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcApplication2.Models.User>" %>
<div>
  <%if (Model != null)
   {%>
   User name: <%=Model.UserName%><br />
   Age: <%=Model.Age%>
  <%} %>
</div>

Home page:


<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication2.Models.User>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
  Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  <h2>Index</h2>
  <%=Html.DropDownList("users", ViewData["users"] as List<SelectListItem>)%>
  <div id="userDetails">
    <%Html.RenderPartial("UserDetails", Model); %>
  </div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="HeadMeta" runat="server">
  <script language="javascript" src="/Scripts/user.js" type="text/javascript"></script>
</asp:Content>

Controller Class:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;
namespace MvcApplication2.Controllers
{
  public class UserController : Controller
  {
    public ActionResult Index()
    {
      List<SelectListItem> userIdList = new List<SelectListItem>();
      foreach (MvcApplication2.Models.User item in MvcApplication2.Models.User.GetUsers())
      {
        userIdList.Add(new SelectListItem { Text = item.UserName,Value = item.UserID.ToString()});
      }
      ViewData["users"] = userIdList;
      MvcApplication2.Models.User user = MvcApplication2.Models.User.GetUsers().FirstOrDefault();
      return View(user);
    }
    public PartialViewResult UserDetails(int? userId)
    {
      MvcApplication2.Models.User user = null;
      if (userId == null)
      {
        user = MvcApplication2.Models.User.GetUsers().FirstOrDefault();
      }
      else
      {
        user = MvcApplication2.Models.User.GetUserById(userId.Value);
      }
      return PartialView(user);
    }
  }
}

We need to specify our PartialView corresponding Action path on the Master page to do this:

Add the following code to Head:


<script language="javascript" type="text/javascript">
    mySite = {
    actions : {
        userDetails: '<%=Url.Action("UserDetails","User")%>'
    }
};
</script>

Our corresponding JS code:


$(document).ready(function () {
  $("#users").change(function () {
    dropDownChange();
  });
});
function dropDownChange() {
  var userId = $("#users").val();
  $.ajax({
    type: "POST",
    url: mySite.actions.userDetails,
    data: { userId: userId },
    success: function (data) {
      $("#userDetails").html(data);
    }
  });
}

This enables you to select the appropriate user and display the corresponding details.

It's just a simple Demo, and I want to help people who need it.

More readers interested in jQuery-related content can view this site's topics: Ajax Usage Summary in jquery, jQuery Table (table) Operation Skills Summary, jQuery Dragging Special Effects and Skills Summary, jQuery Extended Skills Summary, jQuery Common Classic Special Effects Summary, jQuery Animation and Usage Summary,jquery Selector Usage Summary and jQuery Common Plugins and Usage Summary

I hope that the description in this paper will be helpful to everyone's jQuery program design.


Related articles: