MVC + jQuery. Ajax asynchronously implements addition, deletion, modification, query, and paging. mvcjquery. ajax

Source: Internet
Author: User
Tags actionlink

MVC + jQuery. Ajax asynchronously implements addition, deletion, modification, query, and paging. mvcjquery. ajax

The examples in this article share the code for adding, deleting, modifying, and querying pages asynchronously using MVC + jQuery. Ajax for your reference. The details are as follows:

1. Model-Layer Code

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> // obtain the student information List /// </summary> public List <MvcExamples. model. student> StudentList {get; set ;}/// <summary> /// obtain the instructor information List /// </summary> public List <MvcExamples. model. teacher> TeacherList {get; set ;}/// <summary> // obtain the student information list (pagination) /// </summary> public PagedList <MvcExamples. model. student> GetStudentList {get; set ;}}}

2. View-Layer Code

<% @ 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.c Nblogs.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 () {// Add Student Information $ ('# a_add '). click (function () {$ ('# wind Ow '). dialog ({title: "add student information", width: 300, height: 200, modal: true, buttons: {"cancel": function () {$ (this ). dialog ("close"); // close the window when the cancel button is clicked}, and add: function () {// when the Add button is clicked, obtain the value of each parameter var sno =$ ('# sno '). val (); var sname = $ ('# sname '). val (); var ssex = $ ('# ssex '). val (); var sbirsthday =day ('# sbirthday '). val (); var sclass =$ ('# sclass '). val (); $. ajax ({type: 'post', url: '/Student/AddStudent', // The path is the add method data: 'No = '+ Sno + '& name =' + sname + '& sex =' + ssex + '& birsthday =' + sbirsthday + '& sclass =' + sclass, // The number and name of parameters must be consistent with the method name. success: function (json) // return the Json type {$ ('# Windows '). dialog ("close"); // determines whether the request is successful if (json. result = "true") {$ ('# btn_close '). click (); alert ('Congratulations, modification successful! ');} Else {alert (' sorry, modification failed! ') ;}}};}}}) ;}// Deletes Student Information $ ('. a_delete '). click (function () {// confirm whether to delete if (confirm ("whether to delete this message? ") {$. Ajax ({type: 'post', url: '/Student/DeleteStudent', data: 'No = '+ $ (this ). attr ("sno"), // get the sno value of the current object's attributes (custom attributes), and save the required data with custom attributes sucess: function (json) {if (json. result = "true") {alert ("Congratulations, you have deleted it! ");} Else {alert (" sorry, deletion failed! ") ;}}}}) // Modify Student Information $ ('. 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"); $ ('# Windows '). dialog ({title: "modifying student information", width: 300, height: 200, modal: tr Ue, buttons: {"cancel": function () {$ (this ). dialog ("close") ;}, "modify": function () {var sno =$ ('# sno '). val (); var sname = $ ('# sname '). val (); var ssex = $ ('# ssex '). val (); var sbirsthday =day ('# 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) {$ ('# w Indow '). dialog ("close"); if (json. result = "true") {$ ('# btn_close '). click (); alert ('Congratulations, modification successful! ');} Else {alert (' sorry, modification failed! ') ;}}}) ;}}}}) ;}};}) </Script> </asp: Content> <asp: content ID = "Content2" ContentPlaceHolderID = "MainContent" runat = "server"> 

3. Controller Layer Code

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> /// demo /// </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? & Quot; 95031 & quot;: sclass; MvcExamples. web. models. studentModels _ StudentModels = new MvcExamples. web. models. studentModels (); _ StudentModels. studentList = _ Student. getModelList ("sclass =" + sClass); _ StudentModels. teacherList = _ Teacher. getModelList ("tsex = 'male'"); _ StudentModels. getStudentList = new PagedList <MvcExamples. model. student> (_ Student. getModelList ("sclass =" + sClass ). asQueryable (), PageIndex, PageSize); return View (_ StudentModels ); // return a Model} /// <summary> /// modify the student information /// </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> /// Delete student information /// </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> /// add student information /// </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> /// provide the data in the pop-up window /// </summary> /// <param name = "id"> </param> /// <returns> </returns> public ActionResult WindowData (int id) {JsonResult json = new JsonResult (); // json data is provided here (the demo is used here, and the following data is simulated) json. data = new {name = "Michael", sex = "male"}; return json ;}}}

4. Two paging auxiliary classes: PagedList and MikePagerHtmlExtensions

PagedList helper class

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 Tota LPage // total page count {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 helper class

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"); retu Rn 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. vi EwContext. 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 Mi KePager <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, "Homepage", action, controller, vs, null); builder. append (""); vs ["pi"] = data. pageIndex-1; builder. append (Html. linkExtensions. actionLink (html, "Previous Page", action, controller, vs, null); builder. append ("") ;}for (int I = start; I <= end; I ++) // The front and back pages are displayed with 5 numbers {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, "Next page", action, controller, vs, null); builder. append (""); vs ["pi"] = data. totalPage; builder. append (Html. linkExtensions. actionLink (html, "Last page", action, controller, vs, null);} builder. append ("per page" + data. pageSize + "entries/total" + data. totalCount + "entry" + data. pageIndex + "Page/total" + data. totalPage + "page </div>"); return builder. toString () ;}# endregion }}

:

5. Download the source code:JQuery. Ajax asynchronous addition, deletion, modification, query, and paging

The above is all the content of this article, hoping to help you learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.