MVC+jQuery.Ajax는 추가, 삭제, 수정, 쿼리 및 paging_jquery를 비동기식으로 구현합니다.
이 기사의 예에서는 참고용으로 추가, 삭제, 수정 및 페이징의 MVC+jQuery.Ajax 비동기 구현의 특정 코드를 공유합니다.
1. 모델 레이어 코드
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Collections.Generic; using MvcExamples; using System.Web.Mvc; namespace MvcExamples.Web.Models { public class StudentModels { /// <summary> /// 获取学生信息列表 /// </summary> public List<MvcExamples.Model.Student> StudentList { get; set; } /// <summary> /// 获取教工信息列表 /// </summary> public List<MvcExamples.Model.Teacher> TeacherList { get; set; } /// <summary> /// 获取学生信息列表(分页) /// </summary> public PagedList<MvcExamples.Model.Student> GetStudentList { get; set; } } }
2. 레이어 코드 보기
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcExamples.Web.Models.StudentModels>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Index </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server"> <script src="http://www.cnblogs.com/Scripts/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="http://www.cnblogs.com/Scripts/My97DatePicker/WdatePicker.js" type="text/javascript"></script> <script src="http://www.cnblogs.com/Scripts/windwUi/jquery-ui-1.8.1.min.js" type="text/javascript"></script> <link href="http://www.cnblogs.com/Scripts/windwUi/jquery-ui-1.8.1.custom.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> $(function(){ //添加学生信息 $('#a_add').click(function(){ $('#window').dialog({ title: "添加学生信息", width: 300, height: 200, modal: true, buttons: { "取消": function() { $(this).dialog("close"); //当点击取消按钮时,关闭窗口 }, "添加": function() { //当点击添加按钮时,获取各参数的值 var sno=$('#sno').val(); var sname=$('#sname').val(); var ssex=$('#ssex').val(); var sbirsthday=$('#sbirthday').val(); var sclass=$('#sclass').val(); $.ajax({ type:'post', url:'/Student/AddStudent',//路径为添加方法 data:'no='+sno+'&name='+sname+'&sex='+ssex+'&birsthday='+sbirsthday+'&sclass='+sclass,//参数的个数和名字要和方法的名字保持一致 success:function(json)//返回的是Json类型的 { $('#window').dialog("close"); //判断是否成功 if(json.result=="true") { $('#btn_close').click(); alert('恭喜你,修改成功!'); }else{ alert('抱歉,修改失败!'); } } }); } } }); }) //删除学生信息 $('.a_delete').click(function(){ //确认是否删除 if(confirm("是否删除此条信息?")) { $.ajax({ type:'post', url:'/Student/DeleteStudent', data:'no='+$(this).attr("sno"),//获取当前对象的属性(自定义属性)sno的值,用自定义属性保存相应需要的数据 sucess:function(json) { if(json.result=="true") { alert("恭喜你,已成功删除!"); }else { alert("抱歉,删除失败!"); } } }) } }) //修改学生信息 $('.a_update').click(function(){ var student=$(this); $("#sno").attr("value",student.attr("sno")); $("#sname").attr("value",student.attr("sname")); $("#ssex").attr("value",student.attr("ssex")); $("#sbirthday").attr("value",student.attr("sbirthday")); $("#sclass").attr("value",student.attr("sclass")); $('#window').dialog({ title: "修改学生信息", width: 300, height: 200, modal: true, buttons: { "取消": function() { $(this).dialog("close"); }, "修改": function() { var sno=$('#sno').val(); var sname=$('#sname').val(); var ssex=$('#ssex').val(); var sbirsthday=$('#sbirthday').val(); var sclass=$('#sclass').val(); $.ajax({ type:'post', url:'/Student/UpdateStudent', data:'no='+sno+'&name='+sname+'&sex='+ssex+'&birsthday='+sbirsthday+'&sclass='+sclass, success:function(json) { $('#window').dialog("close"); if(json.result=="true") { $('#btn_close').click(); alert('恭喜你,修改成功!'); }else{ alert('抱歉,修改失败!'); } } }); } } }); }); }) </script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2> MVC 演示</h2> <table> <thead> <tr> <td> 学生表 </td> </tr> <tr> <td> 学号 </td> <td> 姓名 </td> <td> 性别 </td> <td> 生日 </td> <td> 班级 </td> <td> 操作 </td> </tr> </thead> <tbody> <%foreach (MvcExamples.Model.Student student in Model.GetStudentList) {%> <tr> <td> <%=student.sno %> </td> <td> <%=student.sname %> </td> <td> <%=student.ssex %> </td> <td> <%=student.sbirthday %> </td> <td> <%=student.sclass %> </td> <td> <a href="javascript:void(0);" class="a_update" sno="<%=student.sno %>" sname="<%=student.sname %>" ssex="<%=student.ssex %>" sbirthday="<%=student.sbirthday %>" sclass="<%=student.sclass %>">修改</a>   <a href="javascript:void(0);" class="a_delete" sno="<%=student.sno %>">删除</a> </td> </tr> <% } %> </tbody> <tfoot> <tr> <td> 全选 </td> <td colspan="5" style="text-align: right;"> <a href="javascript:void(0);" id="a_add">添加</a> </td> </tr> </tfoot> </table> <%=Html.MikePager(Model.GetStudentList)%> <br /> <table> <thead> <tr> <td> 学生表 </td> </tr> <tr> <td> 学号 </td> <td> 姓名 </td> <td> 性别 </td> <td> 生日 </td> <td> 班级 </td> </tr> </thead> <tbody> <%foreach (MvcExamples.Model.Student student in Model.StudentList) {%> <tr> <td> <%=student.sno %> </td> <td> <%=student.sname %> </td> <td> <%=student.ssex %> </td> <td> <%=student.sbirthday %> </td> <td> <%=student.sclass %> </td> </tr> <% } %> </tbody> </table> <br /> <table> <thead> <tr> <td> 老师表 </td> </tr> <tr> <td> 编号 </td> <td> 姓名 </td> <td> 性别 </td> <td> 生日 </td> <td> 职称 </td> <td> 所在部门 </td> </tr> </thead> <tbody> <%foreach (MvcExamples.Model.Teacher teacher in Model.TeacherList) {%> <tr> <td> <%=teacher.tno%> </td> <td> <%=teacher.tname%> </td> <td> <%=teacher.tsex%> </td> <td> <%=teacher.tbirthday%> </td> <td> <%=teacher.prof%> </td> <td> <%=teacher.depart%> </td> </tr> <% } %> </tbody> </table> <div id="window" style="display:none;"> <input type="hidden" id="sno" name="sno" value="" /> 姓名:<input type="text" id="sname" name="sname" /><br /> 性别:<input type="text" id="ssex" name="ssex" /><br /> 生日:<input type="text" id="sbirthday" name="sbirthday" onClick = "WdatePicker()" /><br /> 班级:<input type="text" id="sclass" name="sclass" /><br /> </div> </asp:Content>
3. 컨트롤러 레이어 코드
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; namespace MvcExamples.Web.Controllers { public class StudentController : Controller { // // GET: /Student/ MvcExamples.BLL.Student _Student = new MvcExamples.BLL.Student(); MvcExamples.BLL.Teacher _Teacher = new MvcExamples.BLL.Teacher(); /// <summary> /// 演示 /// </summary> /// <param name="pi"></param> /// <param name="sclass"></param> /// <returns></returns> public ActionResult Index(int? pi, string sclass) { int PageIndex = pi ?? 1; int PageSize = 5; string sClass = sclass == null ? "95031" : sclass; MvcExamples.Web.Models.StudentModels _StudentModels = new MvcExamples.Web.Models.StudentModels(); _StudentModels.StudentList = _Student.GetModelList("sclass=" + sClass); _StudentModels.TeacherList = _Teacher.GetModelList("tsex='男'"); _StudentModels.GetStudentList = new PagedList<MvcExamples.Model.Student>(_Student.GetModelList("sclass=" + sClass).AsQueryable(), PageIndex, PageSize); return View(_StudentModels);//返回一个Model } /// <summary> /// 修改学生信息 /// </summary> /// <param name="no"></param> /// <param name="name"></param> /// <param name="sex"></param> /// <param name="birsthday"></param> /// <param name="sclass"></param> /// <returns></returns> public ActionResult UpdateStudent(string no, string name, string sex, string birsthday, string sclass) { MvcExamples.Model.Student _student = new MvcExamples.Model.Student(); _student.sno = no; _student.sname = name; _student.ssex = sex; _student.sbirthday = Convert.ToDateTime(birsthday); _student.sclass = sclass; _Student.Update(_student); JsonResult json = new JsonResult(); json.Data = new { result = "true" }; return json; } /// <summary> /// 删除学生信息 /// </summary> /// <param name="no"></param> /// <returns></returns> public ActionResult DeleteStudent(string no) { bool IsDelete= _Student.Delete(no); JsonResult json = new JsonResult(); return json; if (IsDelete) { json.Data = new { result = "true" }; } else { json.Data = new { result ="false" }; } return json; } /// <summary> /// 添加学生信息 /// </summary> /// <param name="no"></param> /// <param name="name"></param> /// <param name="sex"></param> /// <param name="birsthday"></param> /// <param name="sclass"></param> /// <returns></returns> public ActionResult AddStudent(string no, string name, string sex, string birsthday, string sclass) { MvcExamples.Model.Student _student = new MvcExamples.Model.Student(); _student.sno = no; _student.sname = name; _student.ssex = sex; _student.sbirthday = Convert.ToDateTime(birsthday); _student.sclass = sclass; _Student.Add(_student); JsonResult json = new JsonResult(); json.Data = new { result = "true" }; return json; } /// <summary> /// 提供弹出窗口的数据 /// </summary> /// <param name="id"></param> /// <returns></returns> public ActionResult WindowData(int id) { JsonResult json = new JsonResult(); //这里给json数据(这里只是演示,下面数据是模拟的) json.Data = new { name = "张三", sex = "男" }; return json; } } }
4. 두 개의 페이징 보조 클래스 PagedList 및 MikePagerHtmlExtensions
PagedList 보조 수업
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Collections.Generic; using System.Collections.Specialized; namespace System.Web.Mvc { public interface IPagedList { int TotalPage //总页数 { get; } int TotalCount { get; set; } int PageIndex { get; set; } int PageSize { get; set; } bool IsPreviousPage { get; } bool IsNextPage { get; } } public class PagedList<T> : List<T>, IPagedList { public PagedList(IQueryable<T> source, int? index, int? pageSize) { if (index == null) { index = 1; } if (pageSize == null) { pageSize = 10; } this.TotalCount = source.Count(); this.PageSize = pageSize.Value; this.PageIndex = index.Value; this.AddRange(source.Skip((index.Value - 1) * pageSize.Value).Take(pageSize.Value)); } public int TotalPage { get { return (int)System.Math.Ceiling((double)TotalCount / PageSize); } } public int TotalCount { get; set; } /// <summary> /// /// </summary> public int PageIndex { get; set; } public int PageSize { get; set; } public bool IsPreviousPage { get { return (PageIndex > 1); } } public bool IsNextPage { get { return ((PageIndex) * PageSize) < TotalCount; } } } public static class Pagination { public static PagedList<T> ToPagedList<T>(this IOrderedQueryable<T> source, int? index, int? pageSize) { return new PagedList<T>(source, index, pageSize); } public static PagedList<T> ToPagedList<T>(this IOrderedQueryable<T> source, int? index) { return new PagedList<T>(source, index, 10); } public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int? index, int? pageSize) { return new PagedList<T>(source, index, pageSize); } public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int? index) { return new PagedList<T>(source, index, 10); } } }
MikePagerHtmlExtensions 도우미 클래스
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Web.Mvc; using System.Web.Routing; using System.Text; namespace System.Web.Mvc { public static class MikePagerHtmlExtensions { #region MikePager 分页控件 public static string MikePager<T>(this HtmlHelper html, PagedList<T> data) { string actioinName = html.ViewContext.RouteData.GetRequiredString("action"); return MikePager<T>(html, data, actioinName); } public static string MikePager<T>(this HtmlHelper html, PagedList<T> data, object values) { string actioinName = html.ViewContext.RouteData.GetRequiredString("action"); return MikePager<T>(html, data, actioinName, values); } public static string MikePager<T>(this HtmlHelper html, PagedList<T> data, string action) { return MikePager<T>(html, data, action, null); } public static string MikePager<T>(this HtmlHelper html, PagedList<T> data, string action, object values) { string controllerName = html.ViewContext.RouteData.GetRequiredString("controller"); return MikePager<T>(html, data, action, controllerName, values); } public static string MikePager<T>(this HtmlHelper html, PagedList<T> data, string action, string controller, object values) { return MikePager<T>(html, data, action, controller, new RouteValueDictionary(values)); } public static string MikePager<T>(this HtmlHelper html, PagedList<T> data, RouteValueDictionary values) { string actioinName = html.ViewContext.RouteData.GetRequiredString("action"); return MikePager<T>(html, data, actioinName, values); } public static string MikePager<T>(this HtmlHelper html, PagedList<T> data, string action, RouteValueDictionary values) { string controllerName = html.ViewContext.RouteData.GetRequiredString("controller"); return MikePager<T>(html, data, action, controllerName, values); } public static string MikePager<T>(this HtmlHelper html, PagedList<T> data, string action, string controller, RouteValueDictionary valuedic) { int start = (data.PageIndex - 5) >= 1 ? (data.PageIndex - 5) : 1; int end = (data.TotalPage - start) > 9 ? start + 9 : data.TotalPage; RouteValueDictionary vs = valuedic == null ? new RouteValueDictionary() : valuedic; var builder = new StringBuilder(); builder.AppendFormat("<div class=\"mike_mvc_pager\">"); if (data.IsPreviousPage) { vs["pi"] = 1; builder.Append(Html.LinkExtensions.ActionLink(html, "首页", action, controller, vs, null)); builder.Append(" "); vs["pi"] = data.PageIndex - 1; builder.Append(Html.LinkExtensions.ActionLink(html, "上一页", action, controller, vs, null)); builder.Append(" "); } for (int i = start; i <= end; i++) //前后各显示5个数字页码 { vs["pi"] = i; if (i == data.PageIndex) { builder.Append("<font class='thispagethis'>" + i.ToString() + "</font> "); } else { builder.Append(" "); builder.Append(Html.LinkExtensions.ActionLink(html, i.ToString(), action, controller, vs, null)); } } if (data.IsNextPage) { builder.Append(" "); vs["pi"] = data.PageIndex + 1; builder.Append(Html.LinkExtensions.ActionLink(html, "下一页", action, controller, vs, null)); builder.Append(" "); vs["pi"] = data.TotalPage; builder.Append(Html.LinkExtensions.ActionLink(html, "末页", action, controller, vs, null)); } builder.Append(" 每页" + data.PageSize + "条/共" + data.TotalCount + "条 第" + data.PageIndex + "页/共" + data.TotalPage + "页 </div>"); return builder.ToString(); } #endregion } }
렌더링:
5. 소스 코드 다운로드: jQuery.Ajax는 추가, 삭제, 수정 및 페이징을 비동기식으로 구현합니다.
위 내용은 이 글의 전체 내용입니다. 모든 분들의 공부에 도움이 되었으면 좋겠습니다.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

각각의 엔진의 구현 원리 및 최적화 전략이 다르기 때문에 JavaScript 엔진은 JavaScript 코드를 구문 분석하고 실행할 때 다른 영향을 미칩니다. 1. 어휘 분석 : 소스 코드를 어휘 단위로 변환합니다. 2. 문법 분석 : 추상 구문 트리를 생성합니다. 3. 최적화 및 컴파일 : JIT 컴파일러를 통해 기계 코드를 생성합니다. 4. 실행 : 기계 코드를 실행하십시오. V8 엔진은 즉각적인 컴파일 및 숨겨진 클래스를 통해 최적화하여 Spidermonkey는 유형 추론 시스템을 사용하여 동일한 코드에서 성능이 다른 성능을 제공합니다.

실제 세계에서 JavaScript의 응용 프로그램에는 서버 측 프로그래밍, 모바일 애플리케이션 개발 및 사물 인터넷 제어가 포함됩니다. 1. 서버 측 프로그래밍은 Node.js를 통해 실현되며 동시 요청 처리에 적합합니다. 2. 모바일 애플리케이션 개발은 재교육을 통해 수행되며 크로스 플랫폼 배포를 지원합니다. 3. Johnny-Five 라이브러리를 통한 IoT 장치 제어에 사용되며 하드웨어 상호 작용에 적합합니다.

일상적인 기술 도구를 사용하여 기능적 다중 테넌트 SaaS 응용 프로그램 (Edtech 앱)을 구축했으며 동일한 작업을 수행 할 수 있습니다. 먼저, 다중 테넌트 SaaS 응용 프로그램은 무엇입니까? 멀티 테넌트 SAAS 응용 프로그램은 노래에서 여러 고객에게 서비스를 제공 할 수 있습니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

Dreamweaver Mac版
시각적 웹 개발 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.
