ASP.NET MVC4+EF4.1+WCF RESTful 实战(二)

忽然发现周围的人都是高级编程人员,而我是介于初级和高级之间。顺便吟诗一首,“千山鸟飞绝,万径人踪灭。野旷天低树,江清月近人。”,,我们进入正题。首先来看一下效果图

 

本篇文章和上篇文章讲的是同一个界面,但是本片讲述的AJAX实现。首先,先看前台代码

  
  
  
  
  1. @using MVCRestServiceDemo.Models.Response;  
  2. @using MVCRestServiceDemo.Models;  
  3. @model DataResponse<person_info> 
  4. <!DOCTYPE html> 
  5. <html> 
  6. <head> 
  7.     <meta name="viewport" content="width=device-width" /> 
  8.     <title>档案信息</title> 
  9.     <script type="text/javascript" src="~/Scripts/jquery-1.6.2.min.js"></script> 
  10.     <script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script> 
  11.     <script type="text/javascript"> 
  12.     jQuery(document).ready(function () {  
  13.         setRowBackColor();  
  14.         $("#btnQuery").click(function () { /*查询*/  
  15.             queryData();  
  16.         });  
  17.     });  
  18.  
  19.     function queryData()  
  20.     {  
  21.         var pageIndex = 1;  
  22.         var pageSize = 10;  
  23.         var no = $("#txtNo").val();  
  24.         var name = $("#txtName").val();  
  25.         var sex = $("#ddlSex").val();  
  26.         var condition = pageIndex + "_" + pageSize + "_" + no + "|" + name + "|" + sex;  
  27.         $.ajax({  
  28.             url: "/Home/GetArchiveInfoByConditionAjax/" + condition,  
  29.             type: "POST",  
  30.             datatype: "Html",  
  31.             beforeSend: function () {  
  32.                 $("#updateProgressDiv").show();  
  33.             },  
  34.             complete: function () {  
  35.                 $("#updateProgressDiv").hide();  
  36.             },  
  37.             success: function (data) {  
  38.                 $("#archiveInfoPartialDiv").html(data);  
  39.                 setRowBackColor();  
  40.             },  
  41.             error: function () {  
  42.                 alert("查询失败!");  
  43.             }  
  44.         });  
  45.     }  
  46.     function checkall() {   /*全选*/  
  47.         if ($("#chkall").attr("checked")) {  
  48.             $(".mytable :checkbox").attr("checked", true);  
  49.         }  
  50.         else {  
  51.             $(".mytable :checkbox").attr("checked", false);  
  52.         }  
  53.     }  
  54.     function setRowBackColor() /*隔行变色*/ {  
  55.         var t = document.getElementById("tabArchiveInfo").getElementsByTagName("tr");  
  56.         for (var i = 0; i < t.length; i++) {  
  57.             t[i].style.backgroundColor = (t[i].sectionRowIndex % 2 == 0) ? "#b7b3b3" : "#fff";  
  58.         }  
  59.     }  
  60.     function setCheck(id) /*点击行选中或取消选中行首复选框*/ {  
  61.         $("#chk_" + id).attr("checked", !$("#chk_" + id).attr("checked"));  
  62.     }  
  63.     function ShowArchiveInfoModify(no) {  
  64.         var w = (screen.width - 500) / 2;  
  65.         var h = (screen.height - 210) / 2;  
  66.         var paramStr = "dialogWidth=500px;dialogHeight=210px;dialogTop=" + h + "px;dialogLeft=" + w + "px;center=yes;middle=yes;help=no;status=no;scroll=no;resizable:no;location:no;";  
  67.         window.showModalDialog("/Home/ShowArchiveInfoModify/" + no, null, paramStr);  
  68.         queryData();  
  69.     }  
  70.     </script> 
  71. </head> 
  72. <body> 
  73.     <div style="margin: 10px" align="center"> 
  74.         @using (Ajax.BeginForm("Delete", "Home", new AjaxOptions() { HttpMethod = "POST"UpdateTargetId = "archiveInfoPartialDiv"InsertionModeInsertionMode = InsertionMode.Replace }))  
  75.         {  
  76.             <table style="width: 96%; margin-bottom: 3px"> 
  77.                 <tr> 
  78.                     <td align="right">档案编号: </td> 
  79.                     <td align="left"> 
  80.                         @Html.TextBox("no", string.Empty,new { id = "txtNo" })  
  81.                     </td> 
  82.                     <td align="right">姓名: </td> 
  83.                     <td align="left"> 
  84.                         @Html.TextBox("name",  string.Empty, new { id = "txtName" })  
  85.                     </td> 
  86.                     <td align="right">性别: </td> 
  87.                     <td align="left"> 
  88.                         @Html.DropDownList("sex", (TempData["selectList"] as SelectList), new { id = "ddlSex" })  
  89.                     </td> 
  90.                     <td aling="center"> 
  91.                         <input id="btnQuery" type="button" value="查询" style="width: 80px" /> 
  92.                     </td> 
  93.                 </tr> 
  94.             </table>           
  95.             Html.RenderPartial("~/Views/PartialView/ArchiveInfoUserControl.cshtml");  
  96.             <div style="width: 96%; margin-top: 5px" align="right"> 
  97.                 <button type="button" style="width: 80px;">增加</button> 
  98.                 <button type="button" style="width: 80px" id="btnDelete">删除</button> 
  99.             </div> 
  100.         }  
  101.     </div> 
  102.     <div id="updateProgressDiv" style="display: none;text-align: center"> 
  103.         <img src="~/Images/throbber.gif" alt="loading" /> 
  104.         <label>正在加载,请稍后......</label> 
  105.     </div> 
  106. </body> 
  107. </html> 

我们看这个queryData函数,查询的时候用的AJAX方式,当回调回来以后,将界面输出至archiveInfoPartialDiv这个DIV。这个DIV在哪呢?我们发现上面的代码中没有,那它肯定在用户控件里面了。

  
  
  
  
  1. @using MVCRestServiceDemo.Models.Response;  
  2. @using MVCRestServiceDemo.Models;  
  3. @model DataResponse<person_info> 
  4. <div id="archiveInfoPartialDiv"> 
  5.     <table class="mytable" id="tabArchiveInfo"> 
  6.         <tr> 
  7.             <th> 
  8.                 <center> 
  9.                     @Html.CheckBox("chk_all", new { id = "chkall"onclick = "checkall()" })  
  10.                 </center> 
  11.             </th> 
  12.             <th> 
  13.                 <center>档案编号</center> 
  14.             </th> 
  15.             <th> 
  16.                 <center>姓名</center> 
  17.             </th> 
  18.             <th> 
  19.                 <center>性别</center> 
  20.             </th> 
  21.             <th> 
  22.                 <center>身份证号</center> 
  23.             </th> 
  24.             <th> 
  25.                 <center>出生日期</center> 
  26.             </th> 
  27.             <th> 
  28.                 <center>毕业院校</center> 
  29.             </th> 
  30.             <th> 
  31.                 <center>学历</center> 
  32.             </th> 
  33.             <th> 
  34.                 <center>专业</center> 
  35.             </th> 
  36.             <th> 
  37.                 <center>操作</center> 
  38.             </th> 
  39.         </tr> 
  40.         @foreach (var personInfo in Model.DataList)  
  41.         {  
  42.             <tr onclick="setCheck('@personInfo.id')"> 
  43.                 <td style="text-align: center;"> 
  44.                     @Html.CheckBox(string.Concat("chk_", personInfo.id), false, new { id = string.Concat("chk_", personInfo.id), onclick = "setCheck('" + personInfo.id + "')" })  
  45.                     @Html.Hidden(string.Concat("hfd_", personInfo.id), personInfo.id)  
  46.                 </td> 
  47.                 <td> 
  48.                     @personInfo.no  
  49.                 </td> 
  50.                 <td> 
  51.                     @personInfo.name  
  52.                 </td> 
  53.                 <td> 
  54.                     @(personInfo.sex == "1" ? "男" : "女")  
  55.                 </td> 
  56.                 <td> 
  57.                     @personInfo.id_card  
  58.                 </td> 
  59.                 <td> 
  60.                     @personInfo.birth  
  61.                 </td> 
  62.                 <td> 
  63.                     @personInfo.graduate_school  
  64.                 </td> 
  65.                 <td> 
  66.                     @personInfo.education_level  
  67.                 </td> 
  68.                 <td> 
  69.                     @personInfo.professional  
  70.                 </td> 
  71.                 <td> 
  72.                     <button type="button" style="width: 60px; margin-right: 3px" onclick="ShowArchiveInfoModify('@personInfo.id')"> 
  73.                         修改  
  74.                     </button> 
  75.                     <button type="submit" style="width: 60px">删除</button> 
  76.                 </td> 
  77.             </tr> 
  78.         }  
  79.     </table> 
  80.     <div class="divpager"> 
  81.         共有 <font color="red" id="ft">@Model.TotalCount</font>条记录 当前是第 <font color="red">@Model.PageIndex</font> 
  82.         页 共<font color="red">@Model.TotalPages</font>页&nbsp;&nbsp;&nbsp;&nbsp;  
  83.         @if (Model.HasPreviousPage)  
  84.         {  
  85.             @Ajax.ActionLink("首页", "GetArchiveInfoByConditionAjax", new { id = string.Join("_", "1", Model.PageSize, ViewBag.Conition) }, new AjaxOptions() { HttpMethod = "Get"InsertionModeInsertionMode = InsertionMode.Replace, UpdateTargetId = "archiveInfoPartialDiv",LoadingElementId="updateProgressDiv"OnSuccess="setRowBackColor();" })<label>&nbsp;  
  86.             </label> 
  87.             @Ajax.ActionLink("上一页", "GetArchiveInfoByConditionAjax", new { id = string.Join("_", Model.PageIndex - 1, Model.PageSize, ViewBag.Conition) }, new AjaxOptions() { HttpMethod = "Get"InsertionModeInsertionMode = InsertionMode.Replace, UpdateTargetId = "archiveInfoPartialDiv",LoadingElementId="updateProgressDiv"OnSuccess="setRowBackColor();" })<label>&nbsp;  
  88.             </label>   
  89.         }  
  90.         else  
  91.         {  
  92.             <text>首页&nbsp;</text> 
  93.             <text>上一页&nbsp;</text> 
  94.         }  
  95.         @if (Model.HasNextPage)  
  96.         {  
  97.             @Ajax.ActionLink("下一页", "GetArchiveInfoByConditionAjax", new { id = string.Join("_", Model.PageIndex + 1, Model.PageSize, ViewBag.Conition) }, new AjaxOptions() { HttpMethod = "Get"InsertionModeInsertionMode = InsertionMode.Replace, UpdateTargetId = "archiveInfoPartialDiv",LoadingElementId="updateProgressDiv"OnSuccess="setRowBackColor();" })<label>&nbsp;  
  98.             </label> 
  99.             @Ajax.ActionLink("末页", "GetArchiveInfoByConditionAjax", new { id = string.Join("_", Model.TotalPages, Model.PageSize, ViewBag.Conition) }, new AjaxOptions() { HttpMethod = "Get"InsertionModeInsertionMode = InsertionMode.Replace, UpdateTargetId = "archiveInfoPartialDiv",LoadingElementId="updateProgressDiv" , OnSuccess="setRowBackColor();"})  
  100.         }  
  101.         else  
  102.         {  
  103.             <text>下一页&nbsp;</text>   
  104.             <text>末页&nbsp;</text> 
  105.         }  
  106.     </div> 
  107. </div> 

果然在这里。在第一段代码中,我们在点击修改按钮的时候弹出一个修改界面,即ShowArchiveInfoModify函数,这个函数接收一个参数,然后调用"/Home/ShowArchiveInfoModify/" + no这个URL,Modal页面修改完数据关闭的时候,调用queryData函数异步刷新界面。我们看到这个代码 @Ajax.ActionLink("首页", "GetArchiveInfoByConditionAjax", new { id = string.Join("_", "1", Model.PageSize, ViewBag.Conition) }, new AjaxOptions() { HttpMethod = "Get", InsertionMode = InsertionMode.Replace, UpdateTargetId = "archiveInfoPartialDiv",LoadingElementId="updateProgressDiv", OnSuccess="setRowBackColor();" })。这就是我们的AJAX方式分页。关于这个Ajax.ActionLink有很多重载,具体的自己看。我这个第一个参数是超链接名字,第二个参数是Action名字,第三个参数是RouteValues,第四个参数AjaxOptions。关于这个AjaxOptions,我们看看

这个Confirm是确认信息,假如你这个链接是删除,那么你可以设置Confirm="确定要删除吗?"。如果你确定,那么就执行删除的Action,否则不执行。看到这个LoadingElementDuration,这个是指加载界面元素时弹出UpdateProgress的事件间隔,比如淘宝上查询了一批商品,那么会出一个显示正在加载的圆圈。LoadingElementID指的是显示正在加载的元素的ID,比如<div id="loadingelmentId">正在加载.......</div>。在这里我们可以看到是

  
  
  
  
  1. <div id="updateProgressDiv" style="display: none;text-align: center"> 
  2.         <img src="~/Images/throbber.gif" alt="loading" /> 
  3.         <label>正在加载,请稍后......</label> 
  4.     </div> 

这个层,当分页调用的时候就显示这个层,调用成功该层隐藏,注意,初始化的层是隐藏的display: none。看到这里,我们发现queryData的代码如下

  
  
  
  
  1. $.ajax({  
  2.             url: "/Home/GetArchiveInfoByConditionAjax/" + condition,  
  3.             type: "POST",  
  4.             datatype: "Html",  
  5.             beforeSend: function () {  
  6.                 $("#updateProgressDiv").show();  
  7.             },  
  8.             complete: function () {  
  9.                 $("#updateProgressDiv").hide();  
  10.             },  
  11.             success: function (data) {  
  12.                 $("#archiveInfoPartialDiv").html(data);  
  13.                 setRowBackColor();  
  14.             },  
  15.             error: function () {  
  16.                 alert("查询失败!");  
  17.             }  
  18.         }); 

在这里其实用jquery也可以轻松实现loading效果,主要的就是beforesend和complete。OnBegin,就是调用AJAX之前,OnComplete就是调用结束后,OnFailure就是调用失败,OnSuccess就是调用成功,在这里就是当异步调用成功以后,给partial页面设置隔行变色,调用setRowBackColor函数。再下来有一个HttpMethod,这个就是请求的方式POST还是GET。InsertionMode则是插入的方式,比如AJAX调用结束以后,返回的是一个页面cshtml,这个时候你要指定这个InsertionMode

我们看到有三个枚举值,一个是InsertAfter,意思是在之后插入,InsertBefore是在之前插入,Replace则是替换,由于我们在这里是分页,所以肯定是Replace,因为我们每次返回的都是一页数据。有一种场景,可能用到InsertAfter,比如,我增加一个东西,我每次增加完以后我都要看见这个东西增加成功了,这个时候,后台只需要把刚插入的这条返回,然后InsertAfter即可。InsertBefore场景比如我点击删除,然后后台返回一个由于什么原因不能删除的信息,这个时候可以显示在form的最顶,就用InsertBefore,总之InsertAfterBefore强调的增量,而Replace强调的是覆盖。最后的一个参数UpdateTargetId,意思是要更改的元素ID,一般是DIV。在这里我们每次分页要更新的是archiveInfoPartialDiv这个DIV元素。OK,前台基本没什么了。我们看看后台

  
  
  
  
  1. #region ajax page  
  2.         public ViewResult GetArchiveInfoAjax()  
  3.         {  
  4.             string uri = string.Format(baseAddress + "PersonInfo/GetAll/{0}/{1}", 1, 10);  
  5.             ViewBag.Conition = string.Join("|"string.Empty, string.Empty, string.Empty);  
  6.             DataResponse<person_info> personInfoList = dataService.GetData<DataResponse<person_info>>(uri);  
  7.             this.GetSexList();  
  8.             return View("~/Views/Home/ArchiveInfoAjax.cshtml", personInfoList);  
  9.         }  
  10.  
  11.         public PartialViewResult GetArchiveInfoByConditionAjax(string id)  
  12.         {  
  13.             string[] pageValues = id.Split("_".ToCharArray());  
  14.             int pageIndex = int.Parse(pageValues.ElementAt(0));  
  15.             int pageSize = int.Parse(pageValues.ElementAt(1));  
  16.             string[] searchValues = pageValues[2].Split("|".ToCharArray());  
  17.             string no = searchValues.ElementAt(0) ?? string.Empty;  
  18.             string name = searchValues.ElementAt(1) ?? string.Empty;  
  19.             string sex = searchValues.ElementAt(2) ?? string.Empty;  
  20.             PersonRequest request = new PersonRequest()  
  21.             {  
  22.                 No = no.Trim(),  
  23.                 Name = name.Trim(),  
  24.                 Sex = sex.Trim(),  
  25.                 PageSize = pageSize,  
  26.                 PageIndex = pageIndex  
  27.             };  
  28.             ViewBag.No = request.No;  
  29.             ViewBag.Name = request.Name;  
  30.             ViewBag.Conition = string.Join("|", no.Trim(), name.Trim(), sex.Trim());  
  31.             string uri = baseAddress + "PersonInfo/GetByCondition";  
  32.             DataResponse<person_info> personInfoList = dataService.GetData<DataResponse<person_info>, PersonRequest>(uri, request);  
  33.             return PartialView("~/Views/PartialView/ArchiveInfoUserControl.cshtml", personInfoList);  
  34.         }  
  35.  
  36.         public ViewResult ShowArchiveInfoModify(string id)  
  37.         {  
  38.             string uri = string.Format(string.Concat(baseAddress, "PersonInfo/GetPersonInfo/{0}"),id);  
  39.             person_info personInfo = dataService.GetData<person_info>(uri);  
  40.             this.GetSexList(string.Empty);  
  41.             this.GetEducationList(string.Empty);  
  42.             this.GetProfessionalList(string.Empty);  
  43.             return View("~/Views/Home/ArchiveInfoModify.cshtml",personInfo);  
  44.         }  
  45.  
  46.         public JavaScriptResult ModifyPersonInfo(person_info personInfo)  
  47.         {  
  48.             if (string.IsNullOrEmpty(personInfo.education_level))  
  49.             {  
  50.                 return JavaScript("alert('学历不能为空!');");  
  51.             }  
  52.             string uri = string.Concat(baseAddress, "PersonInfo/ModifyPersonInfo");  
  53.             int suc=dataService.DealData<int, person_info>(uri,personInfo);  
  54.             return JavaScript("alert('修改成功!');window.close();");  
  55.         }  
  56.  
  57.         private void GetEducationList(string selectedValue="")  
  58.         {  
  59.             string uri = baseAddress + "PersonInfo/GetEducation";  
  60.             List<codes> codeList = dataService.GetData<List<codes>>(uri);  
  61.             codeList.Insert(0, new codes() { data = string.Empty, display_content = "---请选择---" });  
  62.             SelectList selectList = new SelectList(codeList, "data""display_content", selectedValue);  
  63.             ViewBag.EducationList = selectList;  
  64.         }  
  65.  
  66.         private void GetProfessionalList(string selectedValue = "")  
  67.         {  
  68.             string uri = baseAddress + "PersonInfo/GetProfessional";  
  69.             List<codes> codeList = dataService.GetData<List<codes>>(uri);  
  70.             codeList.Insert(0, new codes() { data = string.Empty, display_content = "---请选择---" });  
  71.             SelectList selectList = new SelectList(codeList, "data""display_content", selectedValue);  
  72.             ViewBag.ProfessionalList = selectList;  
  73.         }  
  74.  
  75.         #endregion 

一些获取下拉列表数据,查询,获取Modal页面,修改信息。GetArchiveInfoAjax这个是初始化界面,GetArchiveInfoByConditionAjax这个是分页,和非AJAX界面不同的是,它返回的是我们的partial页PartialView("~/Views/PartialView/ArchiveInfoUserControl.cshtml", personInfoList)用这个页面去替换上一页数据。ShowArchiveInfoModify界面则是返回showModal界面,并且给它绑定一个要修改的对象。ModifyPersonInfo就是修改信息了,在这里我们写了一个简单的check,然后return JavaScript("alert('学历不能为空!');"),注意在这里,如果return JavaScript,则要在页面引用jquery.unobtrusive-ajax.min.js,否则不能正确执行javascript。好了,我们再看看我们的WCF Service

  
  
  
  
  1. public person_info GetPersonInfo(string id)  
  2.         {  
  3.             person_info personInfo = misInfoEntities.person_info.Find(id);  
  4.             return personInfo;  
  5.         }  
  6.  
  7.         public int ModifyPersonInfo(person_info personInfo)  
  8.         {  
  9.             person_info person_Info = misInfoEntities.person_info.Find(personInfo.id);  
  10.             person_Info.name = personInfo.name;  
  11.             person_Info.id_card = personInfo.id_card;  
  12.             person_Info.sex = personInfo.sex;  
  13.             person_Info.education_level = personInfo.education_level;  
  14.             person_Info.professional = personInfo.professional;  
  15.             person_Info.graduate_school = personInfo.graduate_school;  
  16.             person_Info.graduate_year = personInfo.graduate_year;  
  17.             person_Info.contact_tel = personInfo.contact_tel;  
  18.             misInfoEntities.Entry<person_info>(person_Info).State = EntityState.Modified;  
  19.             return misInfoEntities.SaveChanges();  
  20.         } 

没什么可说的,很简单,今天就到这里,我还没写完呢,就被评为推荐,在此谢过,收拾上班。

你可能感兴趣的:(jquery,mvc,asp.net,ef)