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

  1 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcExamples.Web.Models.StudentModels>" %>
2
3 <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
4 Index
5 </asp:Content>
6 <asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
7
8 <script src="http://www.cnblogs.com/Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
9 <script src="http://www.cnblogs.com/Scripts/My97DatePicker/WdatePicker.js" type="text/javascript"></script>
10 <script src="http://www.cnblogs.com/Scripts/windwUi/jquery-ui-1.8.1.min.js" type="text/javascript"></script>
11 <link href="http://www.cnblogs.com/Scripts/windwUi/jquery-ui-1.8.1.custom.css" rel="stylesheet" type="text/css" />
12 <script type="text/javascript">
13 $(function(){
14
15 //添加学生信息
16 $('#a_add').click(function(){
17 $('#window').dialog({
18 title: "添加学生信息",
19 width: 300,
20 height: 200,
21 modal: true,
22 buttons: {
23 "取消": function() {
24 $(this).dialog("close"); //当点击取消按钮时,关闭窗口
25 },
26 "添加": function() {
27 //当点击添加按钮时,获取各参数的值
28 var sno=$('#sno').val();
29 var sname=$('#sname').val();
30 var ssex=$('#ssex').val();
31 var sbirsthday=$('#sbirthday').val();
32 var sclass=$('#sclass').val();
33 $.ajax({
34 type:'post',
35 url:'/Student/AddStudent',//路径为添加方法
36 data:'no='+sno+'&name='+sname+'&sex='+ssex+'&birsthday='+sbirsthday+'&sclass='+sclass,//参数的个数和名字要和方法的名字保持一致
37 success:function(json)//返回的是Json类型的
38 {
39 $('#window').dialog("close");
40 //判断是否成功
41 if(json.result=="true")
42 {
43 $('#btn_close').click();
44 alert('恭喜你,修改成功!');
45 }else{
46 alert('抱歉,修改失败!');
47 }
48 }
49 });
50 }
51 }
52 });
53 })
54
55 //删除学生信息
56 $('.a_delete').click(function(){
57 //确认是否删除
58 if(confirm("是否删除此条信息?"))
59 {
60 $.ajax({
61 type:'post',
62 url:'/Student/DeleteStudent',
63 data:'no='+$(this).attr("sno"),//获取当前对象的属性(自定义属性)sno的值,用自定义属性保存相应需要的数据
64 sucess:function(json)
65 {
66 if(json.result=="true")
67 {
68 alert("恭喜你,已成功删除!");
69 }else
70 {
71 alert("抱歉,删除失败!");
72 }
73 }
74 })
75 }
76 })
77
78 //修改学生信息
79 $('.a_update').click(function(){
80 var student=$(this);
81 $("#sno").attr("value",student.attr("sno"));
82 $("#sname").attr("value",student.attr("sname"));
83 $("#ssex").attr("value",student.attr("ssex"));
84 $("#sbirthday").attr("value",student.attr("sbirthday"));
85 $("#sclass").attr("value",student.attr("sclass"));
86
87 $('#window').dialog({
88 title: "修改学生信息",
89 width: 300,
90 height: 200,
91 modal: true,
92 buttons: {
93 "取消": function() {
94 $(this).dialog("close");
95 },
96 "修改": function() {
97 var sno=$('#sno').val();
98 var sname=$('#sname').val();
99 var ssex=$('#ssex').val();
100 var sbirsthday=$('#sbirthday').val();
101 var sclass=$('#sclass').val();
102 $.ajax({
103 type:'post',
104 url:'/Student/UpdateStudent',
105 data:'no='+sno+'&name='+sname+'&sex='+ssex+'&birsthday='+sbirsthday+'&sclass='+sclass,
106 success:function(json)
107 {
108 $('#window').dialog("close");
109 if(json.result=="true")
110 {
111 $('#btn_close').click();
112 alert('恭喜你,修改成功!');
113 }else{
114 alert('抱歉,修改失败!');
115 }
116 }
117 });
118 }
119 }
120 });
121 });
122
123 })
124 </script>
125
126 </asp:Content>
127 <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
128 <h2>
129 MVC 演示</h2>
130 <table>
131 <thead>
132 <tr>
133 <td>
134 学生表
135 </td>
136 </tr>
137 <tr>
138 <td>
139 学号
140 </td>
141 <td>
142 姓名
143 </td>
144 <td>
145 性别
146 </td>
147 <td>
148 生日
149 </td>
150 <td>
151 班级
152 </td>
153 <td>
154 操作
155 </td>
156 </tr>
157 </thead>
158 <tbody>
159 <%foreach (MvcExamples.Model.Student student in Model.GetStudentList)
160 {%>
161 <tr>
162 <td>
163 <%=student.sno %>
164 </td>
165 <td>
166 <%=student.sname %>
167 </td>
168 <td>
169 <%=student.ssex %>
170 </td>
171 <td>
172 <%=student.sbirthday %>
173 </td>
174 <td>
175 <%=student.sclass %>
176 </td>
177 <td>
178 <a href="javascript:void(0);" class="a_update" sno="<%=student.sno %>" sname="<%=student.sname %>" ssex="<%=student.ssex %>"
179 sbirthday="<%=student.sbirthday %>" sclass="<%=student.sclass %>">修改</a>
180 &nbsp;&nbsp
181 <a href="javascript:void(0);" class="a_delete" sno="<%=student.sno %>">删除</a>
182 </td>
183 </tr>
184 <% } %>
185 </tbody>
186 <tfoot>
187 <tr>
188 <td>
189 全选
190 </td>
191 <td colspan="5" style="text-align: right;">
192 <a href="javascript:void(0);" id="a_add">添加</a>
193 </td>
194 </tr>
195 </tfoot>
196 </table>
197 <%=Html.MikePager(Model.GetStudentList)%>
198 <br />
199 <table>
200 <thead>
201 <tr>
202 <td>
203 学生表
204 </td>
205 </tr>
206 <tr>
207 <td>
208 学号
209 </td>
210 <td>
211 姓名
212 </td>
213 <td>
214 性别
215 </td>
216 <td>
217 生日
218 </td>
219 <td>
220 班级
221 </td>
222 </tr>
223 </thead>
224 <tbody>
225 <%foreach (MvcExamples.Model.Student student in Model.StudentList)
226 {%>
227 <tr>
228 <td>
229 <%=student.sno %>
230 </td>
231 <td>
232 <%=student.sname %>
233 </td>
234 <td>
235 <%=student.ssex %>
236 </td>
237 <td>
238 <%=student.sbirthday %>
239 </td>
240 <td>
241 <%=student.sclass %>
242 </td>
243 </tr>
244 <% } %>
245 </tbody>
246 </table>
247 <br />
248 <table>
249 <thead>
250 <tr>
251 <td>
252 老师表
253 </td>
254 </tr>
255 <tr>
256 <td>
257 编号
258 </td>
259 <td>
260 姓名
261 </td>
262 <td>
263 性别
264 </td>
265 <td>
266 生日
267 </td>
268 <td>
269 职称
270 </td>
271 <td>
272 所在部门
273 </td>
274 </tr>
275 </thead>
276 <tbody>
277 <%foreach (MvcExamples.Model.Teacher teacher in Model.TeacherList)
278 {%>
279 <tr>
280 <td>
281 <%=teacher.tno%>
282 </td>
283 <td>
284 <%=teacher.tname%>
285 </td>
286 <td>
287 <%=teacher.tsex%>
288 </td>
289 <td>
290 <%=teacher.tbirthday%>
291 </td>
292 <td>
293 <%=teacher.prof%>
294 </td>
295 <td>
296 <%=teacher.depart%>
297 </td>
298 </tr>
299 <% } %>
300 </tbody>
301 </table>
302
303 <div id="window" style="display:none;">
304 <input type="hidden" id="sno" name="sno" value="" />
305 姓名:<input type="text" id="sname" name="sname" /><br />
306 性别:<input type="text" id="ssex" name="ssex" /><br />
307 生日:<input type="text" id="sbirthday" name="sbirthday" onClick = "WdatePicker()" /><br />
308 班级:<input type="text" id="sclass" name="sclass" /><br />
309 </div>
310 </asp:Content>


3、Controller层代码

  1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.Mvc;
6 using System.Web.Mvc.Ajax;
7
8 namespace MvcExamples.Web.Controllers
9 {
10 public class StudentController : Controller
11 {
12 //
13         // GET: /Student/
14
15 MvcExamples.BLL.Student _Student = new MvcExamples.BLL.Student();
16 MvcExamples.BLL.Teacher _Teacher = new MvcExamples.BLL.Teacher();
17 /// <summary>
18         /// 演示
19         /// </summary>
20         /// <param name="pi"></param>
21         /// <param name="sclass"></param>
22         /// <returns></returns>
23 public ActionResult Index(int? pi, string sclass)
24 {
25 int PageIndex = pi ?? 1;
26 int PageSize = 5;
27 string sClass = sclass == null ? "95031" : sclass;
28 MvcExamples.Web.Models.StudentModels _StudentModels = new MvcExamples.Web.Models.StudentModels();
29 _StudentModels.StudentList = _Student.GetModelList("sclass=" + sClass);
30 _StudentModels.TeacherList = _Teacher.GetModelList("tsex='男'");
31 _StudentModels.GetStudentList = new PagedList<MvcExamples.Model.Student>(_Student.GetModelList("sclass=" + sClass).AsQueryable(), PageIndex, PageSize);
32 return View(_StudentModels);//返回一个Model
33 }
34 /// <summary>
35         /// 修改学生信息
36         /// </summary>
37         /// <param name="no"></param>
38         /// <param name="name"></param>
39         /// <param name="sex"></param>
40         /// <param name="birsthday"></param>
41         /// <param name="sclass"></param>
42         /// <returns></returns>
43 public ActionResult UpdateStudent(string no, string name, string sex, string birsthday, string sclass)
44 {
45 MvcExamples.Model.Student _student = new MvcExamples.Model.Student();
46 _student.sno = no;
47 _student.sname = name;
48 _student.ssex = sex;
49 _student.sbirthday = Convert.ToDateTime(birsthday);
50 _student.sclass = sclass;
51
52 _Student.Update(_student);
53
54 JsonResult json = new JsonResult();
55 json.Data = new
56 {
57 result = "true"
58 };
59 return json;
60 }
61 /// <summary>
62         /// 删除学生信息
63         /// </summary>
64         /// <param name="no"></param>
65         /// <returns></returns>
66 public ActionResult DeleteStudent(string no)
67 {
68 bool IsDelete= _Student.Delete(no);
69 JsonResult json = new JsonResult();
70 return json;
71 if (IsDelete)
72 {
73 json.Data = new
74 {
75 result = "true"
76 };
77 }
78 else
79 {
80 json.Data = new
81 {
82 result ="false"
83 };
84 }
85 return json;
86 }
87 /// <summary>
88         /// 添加学生信息
89         /// </summary>
90         /// <param name="no"></param>
91         /// <param name="name"></param>
92         /// <param name="sex"></param>
93         /// <param name="birsthday"></param>
94         /// <param name="sclass"></param>
95         /// <returns></returns>
96 public ActionResult AddStudent(string no, string name, string sex, string birsthday, string sclass)
97 {
98 MvcExamples.Model.Student _student = new MvcExamples.Model.Student();
99 _student.sno = no;
100 _student.sname = name;
101 _student.ssex = sex;
102 _student.sbirthday = Convert.ToDateTime(birsthday);
103 _student.sclass = sclass;
104
105 _Student.Add(_student);
106
107 JsonResult json = new JsonResult();
108 json.Data = new
109 {
110 result = "true"
111 };
112 return json;
113 }
114
115 /// <summary>
116         /// 提供弹出窗口的数据
117         /// </summary>
118         /// <param name="id"></param>
119         /// <returns></returns>
120 public ActionResult WindowData(int id)
121 {
122 JsonResult json = new JsonResult();
123 //这里给json数据(这里只是演示,下面数据是模拟的)
124 json.Data = new
125 {
126 name = "张三",
127 sex = ""
128 };
129 return json;
130 }
131
132 }
133 }


4、两个分页辅助类PagedList和MikePagerHtmlExtensions
PagedList辅助类

View Code
  1 using System;
2 using System.Data;
3 using System.Configuration;
4 using System.Linq;
5 using System.Web;
6 using System.Web.Security;
7 using System.Web.UI;
8 using System.Web.UI.HtmlControls;
9 using System.Web.UI.WebControls;
10 using System.Web.UI.WebControls.WebParts;
11 using System.Xml.Linq;
12 using System.Collections.Generic;
13 using System.Collections.Specialized;
14
15 namespace System.Web.Mvc
16 {
17 public interface IPagedList
18 {
19 int TotalPage //总页数
20 {
21 get;
22 }
23
24 int TotalCount
25 {
26 get;
27 set;
28 }
29
30 int PageIndex
31 {
32 get;
33 set;
34 }
35
36 int PageSize
37 {
38 get;
39 set;
40 }
41
42 bool IsPreviousPage
43 {
44 get;
45 }
46
47 bool IsNextPage
48 {
49 get;
50 }
51 }
52
53 public class PagedList<T> : List<T>, IPagedList
54 {
55 public PagedList(IQueryable<T> source, int? index, int? pageSize)
56 {
57 if (index == null) { index = 1; }
58 if (pageSize == null) { pageSize = 10; }
59 this.TotalCount = source.Count();
60 this.PageSize = pageSize.Value;
61 this.PageIndex = index.Value;
62 this.AddRange(source.Skip((index.Value - 1) * pageSize.Value).Take(pageSize.Value));
63 }
64
65 public int TotalPage
66 {
67 get { return (int)System.Math.Ceiling((double)TotalCount / PageSize); }
68 }
69
70 public int TotalCount
71 {
72 get;
73 set;
74 }
75 /// <summary>
76 ///
77 /// </summary>
78 public int PageIndex
79 {
80 get;
81 set;
82 }
83
84 public int PageSize
85 {
86 get;
87 set;
88 }
89
90 public bool IsPreviousPage
91 {
92 get
93 {
94 return (PageIndex > 1);
95 }
96 }
97
98 public bool IsNextPage
99 {
100 get
101 {
102 return ((PageIndex) * PageSize) < TotalCount;
103 }
104 }
105
106 }
107
108 public static class Pagination
109 {
110 public static PagedList<T> ToPagedList<T>(this IOrderedQueryable<T> source, int? index, int? pageSize)
111 {
112 return new PagedList<T>(source, index, pageSize);
113 }
114
115 public static PagedList<T> ToPagedList<T>(this IOrderedQueryable<T> source, int? index)
116 {
117 return new PagedList<T>(source, index, 10);
118 }
119
120 public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int? index, int? pageSize)
121 {
122 return new PagedList<T>(source, index, pageSize);
123 }
124
125 public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int? index)
126 {
127 return new PagedList<T>(source, index, 10);
128 }
129 }
130 }

MikePagerHtmlExtensions辅助类

View Code
  1 using System;
2 using System.Data;
3 using System.Configuration;
4 using System.Linq;
5 using System.Web;
6 using System.Web.Security;
7 using System.Web.UI;
8 using System.Web.UI.HtmlControls;
9 using System.Web.UI.WebControls;
10 using System.Web.UI.WebControls.WebParts;
11 using System.Xml.Linq;
12 using System.Web.Mvc;
13 using System.Web.Routing;
14 using System.Text;
15
16 namespace System.Web.Mvc
17 {
18 public static class MikePagerHtmlExtensions
19 {
20
21 #region MikePager 分页控件
22
23 public static string MikePager<T>(this HtmlHelper html, PagedList<T> data)
24 {
25 string actioinName = html.ViewContext.RouteData.GetRequiredString("action");
26 return MikePager<T>(html, data, actioinName);
27 }
28
29 public static string MikePager<T>(this HtmlHelper html, PagedList<T> data, object values)
30 {
31 string actioinName = html.ViewContext.RouteData.GetRequiredString("action");
32 return MikePager<T>(html, data, actioinName, values);
33 }
34
35 public static string MikePager<T>(this HtmlHelper html, PagedList<T> data, string action)
36 {
37 return MikePager<T>(html, data, action, null);
38 }
39
40 public static string MikePager<T>(this HtmlHelper html, PagedList<T> data, string action, object values)
41 {
42 string controllerName = html.ViewContext.RouteData.GetRequiredString("controller");
43 return MikePager<T>(html, data, action, controllerName, values);
44 }
45
46 public static string MikePager<T>(this HtmlHelper html, PagedList<T> data, string action, string controller, object values)
47 {
48 return MikePager<T>(html, data, action, controller, new RouteValueDictionary(values));
49 }
50
51 public static string MikePager<T>(this HtmlHelper html, PagedList<T> data, RouteValueDictionary values)
52 {
53 string actioinName = html.ViewContext.RouteData.GetRequiredString("action");
54 return MikePager<T>(html, data, actioinName, values);
55 }
56
57 public static string MikePager<T>(this HtmlHelper html, PagedList<T> data, string action, RouteValueDictionary values)
58 {
59 string controllerName = html.ViewContext.RouteData.GetRequiredString("controller");
60 return MikePager<T>(html, data, action, controllerName, values);
61 }
62
63 public static string MikePager<T>(this HtmlHelper html, PagedList<T> data, string action, string controller, RouteValueDictionary valuedic)
64 {
65 int start = (data.PageIndex - 5) >= 1 ? (data.PageIndex - 5) : 1;
66 int end = (data.TotalPage - start) > 9 ? start + 9 : data.TotalPage;
67
68 RouteValueDictionary vs = valuedic == null ? new RouteValueDictionary() : valuedic;
69
70 var builder = new StringBuilder();
71 builder.AppendFormat("<div class=\"mike_mvc_pager\">");
72
73 if (data.IsPreviousPage)
74 {
75 vs["pi"] = 1;
76 builder.Append(Html.LinkExtensions.ActionLink(html, "首页", action, controller, vs, null));
77 builder.Append("&nbsp;");
78 vs["pi"] = data.PageIndex - 1;
79 builder.Append(Html.LinkExtensions.ActionLink(html, "上一页", action, controller, vs, null));
80 builder.Append("&nbsp;");
81
82 }
83
84 for (int i = start; i <= end; i++) //前后各显示5个数字页码
85 {
86 vs["pi"] = i;
87 if (i == data.PageIndex)
88 {
89 builder.Append("<font class='thispagethis'>" + i.ToString() + "</font>&nbsp;");
90 }
91 else
92 {
93 builder.Append("&nbsp;");
94
95 builder.Append(Html.LinkExtensions.ActionLink(html, i.ToString(), action, controller, vs, null));
96 }
97 }
98
99 if (data.IsNextPage)
100 {
101 builder.Append("&nbsp;");
102
103 vs["pi"] = data.PageIndex + 1;
104 builder.Append(Html.LinkExtensions.ActionLink(html, "下一页", action, controller, vs, null));
105 builder.Append("&nbsp;");
106
107
108 vs["pi"] = data.TotalPage;
109 builder.Append(Html.LinkExtensions.ActionLink(html, "末页", action, controller, vs, null));
110
111
112 }
113 builder.Append("&nbsp;每页" + data.PageSize + "条/共" + data.TotalCount + "条 第" + data.PageIndex + "页/共" + data.TotalPage + "页 </div>");
114 return builder.ToString();
115 }
116 #endregion
117 }
118 }

 5、效果如下



6、下载demo演示
点击下载 MVC+jQuery.Ajax异步+增删改查和分页.rar
注:数据库在 Data文件夹。
说明:是专门提取出来的例子,所以有些地方可能不符合开发规范和常规,请见谅。呵呵。

posted @ 2012-04-05 10:49  XuebinDing  阅读(16694)  评论(17编辑  收藏  举报