MVC+jQuery.Ajax异步实现增删改查和分页


Posted in Javascript onDecember 22, 2020

本文实例为大家分享了MVC+jQuery.Ajax异步实现增删改查和分页的具体代码,供大家参考,具体内容如下

1、Model层代码

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、View层代码

<%@ 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、Controller层代码

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

效果图:

MVC+jQuery.Ajax异步实现增删改查和分页

MVC+jQuery.Ajax异步实现增删改查和分页

5、源码下砸:jQuery.Ajax异步实现增删改查和分页

以上就是本文的全部内容,希望对大家的学习有所帮助。

Javascript 相关文章推荐
用js实现判断当前网址的来路如果不是指定的来路就跳转到指定页面
May 02 Javascript
7款吸引人眼球的jQuery/CSS3特效实例分享
Apr 25 Javascript
jQuery添加和删除指定标签的方法
Dec 16 Javascript
js无提示关闭浏览器窗口的两种方法分析
Nov 06 Javascript
vue.js将unix时间戳转换为自定义时间格式
Jan 03 Javascript
js实现拖拽功能
Mar 01 Javascript
iview日期控件,双向绑定日期格式的方法
Mar 15 Javascript
Node.js使用Angular简单示例
May 11 Javascript
浅析vue中的provide / inject 有什么用处
Nov 10 Javascript
2分钟实现一个Vue实时直播系统的示例代码
Jun 05 Javascript
vue2.0实现列表数据增加和删除
Jun 17 Javascript
vue props 一次传多个值实例
Jul 22 Javascript
基于Jquery插件Uploadify实现实时显示进度条上传图片
Mar 26 #Javascript
jQuery实现三级菜单的代码
May 09 #Javascript
Boostrap入门准备之border box
May 09 #Javascript
CKEditor无法验证的解决方案(js验证+jQuery Validate验证)
May 09 #Javascript
jQuery代码实现图片墙自动+手动淡入淡出切换效果
May 09 #Javascript
jQuery绑定事件的几种实现方式
May 09 #Javascript
jquery实现左右无缝轮播图
Jul 31 #Javascript
You might like
重置版游戏视频
2020/04/09 魔兽争霸
简单的移动设备检测PHP脚本代码
2011/02/19 PHP
PHP实现通过get方式识别用户发送邮件的方法
2015/07/16 PHP
Thinkphp整合微信支付功能
2016/12/14 PHP
元素的内联事件处理函数的特殊作用域在各浏览器中存在差异
2011/01/12 Javascript
使用ImageMagick进行图片缩放、合成与裁剪(js+python)
2013/09/16 Javascript
浅谈javascript中遇到的字符串对象处理
2016/11/18 Javascript
JavaScript版经典游戏之扫雷游戏完整示例【附demo源码下载】
2016/12/12 Javascript
JavaScript中定义对象原型的两种使用方法
2016/12/15 Javascript
Node.js中的http请求客户端示例(request client)
2017/05/04 Javascript
JS库 Highlightjs 添加代码行号的实现代码
2017/09/13 Javascript
对于js垃圾回收机制的理解
2017/09/14 Javascript
微信小程序上传图片功能(附后端代码)
2020/06/19 Javascript
为jquery的ajax请求添加超时timeout时间的操作方法
2018/09/04 jQuery
小程序云开发如何实现图片上传及发表文字
2019/05/17 Javascript
详解Nuxt.js中使用Element-UI填坑
2019/09/06 Javascript
JavaScript中window和document用法详解
2020/07/28 Javascript
vue通过接口直接下载java生成好的Excel表格案例
2020/10/26 Javascript
[01:04:08]完美世界DOTA2联赛PWL S3 INK ICE vs GXR 第一场 12.16
2020/12/18 DOTA
Python编程入门之Hello World的三种实现方式
2015/11/13 Python
详解如何用OpenCV + Python 实现人脸识别
2017/10/20 Python
快速排序的四种python实现(推荐)
2019/04/03 Python
Python整数对象实现原理详解
2019/07/01 Python
Python3批量移动指定文件到指定文件夹方法示例
2019/09/02 Python
python针对Oracle常见查询操作实例分析
2020/04/30 Python
3种方式实现瀑布流布局小结
2019/09/05 HTML / CSS
大学军训感言200字
2014/02/26 职场文书
党员教师工作决心书
2014/03/13 职场文书
春节联欢会策划方案
2014/05/16 职场文书
标准大学生职业生涯规划书写作指南
2014/09/18 职场文书
群众路线剖析材料怎么写
2014/10/09 职场文书
2014年教师业务工作总结
2014/12/19 职场文书
2016年第16个全民国防教育日宣传活动总结
2016/04/05 职场文书
导游词之平津战役纪念馆
2019/11/04 职场文书
MYSQL(电话号码,身份证)数据脱敏的实现
2021/05/28 MySQL
Go 内联优化让程序员爱不释手
2022/06/21 Golang