1. 程式人生 > >分享一個自己寫的MVC EF 增刪改查 無重新整理分頁程式

分享一個自己寫的MVC EF 增刪改查 無重新整理分頁程式

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow

也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!

               

一、專案之前得新增幾個元件artDialog、MVCPager、kindeditor-4.0。先上幾個效果圖。

 

      

 

                  

 

         

 

                 

 

                 
     1、首先建立一個數據庫,新增一個Peoples表之後在專案中右鍵新增“新建項”,選擇你剛才建立的資料庫和表。

 

                             


     2、加完之後專案中會有個Peoples.edmx,這裡麵包括資料上下文和實體屬性。
     3、在Controllers右鍵新增“PersonController.cs”,選擇強型別檢視,生成對應的檢視

 

                                            


     4、由於是無重新整理的,必須得建立一個分部檢視,最好是在Shared資料夾下新增"_fenye",顯示載入資料的頁面,新增以下程式碼。  

 

 

 

          (1)、@model Webdiyer.WebControls.Mvc.PagedList<無重新整理分頁.People>,返回的是MVCPager中的PagedList。

 

          (2)、JS中,用的是前面介紹的artDialog元件,增改查的功能,他會彈出一個Dialog。方便實用,還有一些視窗的抖動效果。

 

          (3)、加入一個DIV,因為更新資料的時候顯示在哪個DIV,new AjaxOptions { UpdateTargetId = "tableID" }。

 

          (4)、使用的是Ajax.BeginForm,MVC自己提供的無重新整理,和Jquery中的$.Ajax()是一個性質。

 

          (5)、@Ajax.ActionLink()裡有個new{......},寫他的目的是因為,點選完查詢之後,文字框的值就沒有了,排序和分頁大小也沒有了。所以必須得賦值。 

 

          (6)、@Html.AjaxPager用的就是MVCPager的dll。

                   
@model Webdiyer.WebControls.Mvc.PagedList<無重新整理分頁.People>@using [email protected]{    ViewBag.Title = "Index";}<script type="text/javascript">    $(function () {        //新增        $("#Add").click(function () {            art.dialog.open("/Person/Create", { title: "添 加", lock: true, opacity: 0.5, width: 500, height: 500 })        });        $(".Edit").click(function () {            art.dialog.open("/Person/Edit/" + $(this).attr("value"), { title: "編輯", lock: true, opacity: 0.5, width: 500, height: 500 })        });        $(".Display").click(function () {            art.dialog.open("/Person/Details/" + $(this).attr("value"), { title: "檢視", lock: true, opacity: 0.5, width: 500, height: 500 })            //            //或者用Jquery-UI的dialog        });        $(".deleteID").click(function () {            var ids = $(this).attr("hideID");            var link = $(this);            if (confirm("是否刪除?")) {                $.post("/Person/Delete", { id: ids }, function (data) {                    if (data == "OK") {                        alert("刪除成功!");                        link.parent().parent().fadeOut("slow");                        link.parent().parent().fadeIn("slow");                        link.parent().parent().fadeOut("slow");                    }                });            }            return false;        });    });</script><div id="tableID">    @using (Ajax.BeginForm("Index", new AjaxOptions { UpdateTargetId = "tableID" }))    {        <table>            <tr>                <th>                    操作                </th>                <th>                    @Ajax.ActionLink("姓名", "Index", new { OrderBy = ViewBag.OrderName, pagesize = ViewBag.page }, new AjaxOptions { UpdateTargetId = "tableID" })                </th>                <th>                    @Ajax.ActionLink("性別", "Index", new { OrderBy = ViewBag.OrderSex, pagesize = ViewBag.page }, new AjaxOptions { UpdateTargetId = "tableID" })                </th>                <th>                    生日                </th>                <th>                    描述                </th>                <th>                    Discriminator                </th>            </tr>            @foreach (var item in Model)            {                <tr>                    <td>                        @*@Html.ActionLink("Edit", "Edit", new { id = item.ID }) |   *@ <a href ="javascript:void(0)" class="Edit" value="@item.ID">                            編輯</a> <a href ="javascript:void(0)" class="Display" value="@item.ID">檢視</a>                        @Html.ActionLink("刪除", "Delete", new { id = item.ID }, new { @class = "deleteID", hideID = item.ID })                    </td>                    <td>                        @item.Name                    </td>                    <td>                        @(item.Sex ? "" : "")                    </td>                    <td>                        @String.Format("{0:g}", item.Brithday)                    </td>                    <td>                        @Html.Raw(item.Remark)                    </td>                    <td>                        @item.Discriminator                    </td>                </tr>            }        </table>                    @Html.AjaxPager(Model, new PagerOptions()   {       PageIndexParameterName = "id",       ShowDisabledPagerItems = false,       ShowPageIndexBox = true   }, new AjaxOptions() { UpdateTargetId = "tableID", OnBegin = "AjaxStart", OnComplete = "AjaxStop" }, new { OrderBy = ViewBag.current })    }    分頁大小:    @Ajax.ActionLink("2", "", new { pagesize = 2 }, new AjaxOptions { UpdateTargetId = "tableID", OnBegin = "AjaxStart", OnComplete = "AjaxStop" })    @Ajax.ActionLink("5", "", new { pagesize = 5 }, new AjaxOptions { UpdateTargetId = "tableID", OnBegin = "AjaxStart", OnComplete = "AjaxStop" })    @Ajax.ActionLink("10", "", new { pagesize = 10 }, new AjaxOptions { UpdateTargetId = "tableID", OnBegin = "AjaxStart", OnComplete = "AjaxStop" })</div><div id="result"></div>
      前臺View分頁程式碼  

 

 

      5、前面說的是一個區域性頁,當然是要巢狀在一個普通的View中,在這裡是在Index中。

 

                                                       

 

        6、Index裡面的內容: 

 

           (1)、JS引用部分,引用了一些MVC如果無重新整理的話必須新增的JS,前五個全部是,blockUI.JS是AjaxStart()的效果,載入完畢內容後的效果,還有

 
            artDialog.JS是對話方塊的,還有個Jquery-UI的,因為功能裡"生日"欄位用了一個datepicker。
 

           (2)、還記得這個效果嗎?兩種方式:1、TextBox寫擴充套件方法2、直接給加樣式。如:<input type="text" id="nameT" name="Name"  style="background-image: url(/Images/string.png);background-repeat: no-repeat;padding-left: 22px;"/>      

 

                                                          

                         
@model Webdiyer.WebControls.Mvc.PagedList<無重新整理分頁.People>@using [email protected]{    ViewBag.Title = "Index";}<link  href="@Url.Content("~/Content/jquery-ui-1.9.1.custom.min.css")" rel="stylesheet"  type="text/css" /><script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script><script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script><script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script><script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script><script src="@Url.Content("~/Scripts/blockUI.js")" type="text/javascript"></script><script src="@Url.Content("~/Scripts/artDialog/artDialog.js?skin=default")" type="text/javascript"></script><script src="@Url.Content("~/Scripts/artDialog/plugins/iframeTools.js")" type="text/javascript"></script><script src="@Url.Content("~/Scripts/jquery-ui.min.js")" type="text/javascript"></script><script type="text/javascript">    function AjaxStart() { $.blockUI({ message: '正在獲取資料,請稍候...' }); }    function AjaxStop() { $.unblockUI(); }   </script><p>    <input type="submit" id="Add" value="新建" />    <br />              @using (Ajax.BeginForm("Index", new AjaxOptions { UpdateTargetId = "tableID" }))    {        <input type="text" id="nameT" name="Name"  style="background-image: url(/Images/string.png);background-repeat: no-repeat;padding-left: 22px;"/>              <input type="text" id="Brithday" name="Brithday" value="@ViewBag.CurrentBrithday" style="background-image: url(/Images/date.png);background-repeat: no-repeat;padding-left: 22px;"/>               <input type="submit" class="Query" value="查詢"  name="SubAction" />           }     @Html.Partial("_FenYe")</p>
      Index程式碼  

 

 

                (3)、前臺完事,現在去Controller裡,寫程式碼了。其實MVC是這樣一個請求:瀏覽器-->先到Controller裡-->Models-->在View中載入資料。

 

                        1、因為有一個功能是這樣的,點選姓名可以排序,再點選倒序。所以用到了OrderBy。

 

                        2、返回的資料必須是ToPagedList。以便分頁。

 

                        3、最後返回去的View是“_fenye”,分部檢視PartialView。

 

                                   

                          
MvcApplication34Entities1 persons = new MvcApplication34Entities1();                public ActionResult Index(int? id, string OrderBy, string name,int pagesize = 5)        {            ViewBag.current = OrderBy;            ViewBag.page = pagesize;            ViewBag.Name = name;            ViewBag.OrderName = string.IsNullOrEmpty(OrderBy)?"Name Desc":"";            ViewBag.OrderSex = string.IsNullOrEmpty(OrderBy) ? "Sex" : "Sex Desc";            var per3= persons.People.OrderBy(p => p.ID)                .WhereIf(p=>p.Name.Contains(name),!string.IsNullOrEmpty(name))                .ToPagedList(id ?? 1, pagesize);            if (Request.IsAjaxRequest())            {                switch (OrderBy)                {                    case "Name Desc":                        var per = persons.People                        .OrderByDescending(p => p.Name)                        .WhereIf(p => p.Name.Contains(name), !string.IsNullOrEmpty(name))                        .ToPagedList(id ?? 1, pagesize);                        return PartialView("_FenYe", per);                    case "Sex":                        var per1 = persons.People                       .OrderBy(p => p.Sex)                       .WhereIf(p => p.Name.Contains(name), !string.IsNullOrEmpty(name))                       .ToPagedList(id ?? 1, pagesize);                        return PartialView("_FenYe", per1);                    case "Sex Desc":                        var per4 = persons.People                       .OrderByDescending(p => p.Sex)                       .WhereIf(p => p.Name.Contains(name), !string.IsNullOrEmpty(name))                       .ToPagedList(id ?? 1, pagesize);                        return PartialView("_FenYe", per4);                    default:                        var per2 = persons.People                       .OrderBy(p => p.Name)                       .WhereIf(p => p.Name.Contains(name), !string.IsNullOrEmpty(name))                       .ToPagedList(id ?? 1, pagesize);                        return PartialView("_FenYe", per2);                }                                }            else            {                return View(per3);               }                                           }        [HttpPost]        public ActionResult Index(int? id, string name, FormCollection collections,string OrderBy,int pagesize = 5)        {            ViewBag.CurrentName = name;            //ViewBag.CurrentBrithday = Brithday;                       //    var per = persons.People            //    .Where(p=>p.Name.Contains(name))            //    .OrderBy(p => p.Name)            //    .ToPagedList(id ?? 1, pagesize);            //    return PartialView("_FenYe", per);                      var per = persons.People               .Where(p => p.Name.Contains(name))               .OrderBy(p => p.Name)               .ToPagedList(id ?? 1, pagesize);                                return PartialView("_FenYe", per);        }
      Controller  

        7、前面已經實現了Index。接下來實現增刪改查,也比較容易。

 

            (1)增加Controller和View,使用SaveChanges()進行資料庫的儲存!              

                      
        public ActionResult Create()        {                        return View();        }        //        // POST: /Person/Create        [ValidateInput(false)]        [HttpPost]        public ActionResult Create(FormCollection collection)        {            try            {                               // TODO: Add insert logic here                People p = new People();                TryUpdateModel(p, collection);                persons.AddToPeople(p);                persons.SaveChanges();                return Content("<script>alert('新增成功!');window.parent.location.href='/Person/Index'</script>");            }            catch            {                return View();            }        }
      Create Controller                                
@model 無重新整理分頁[email protected]{    ViewBag.Title = "Create";    Layout = "~/Views/Shared/_Ba.cshtml";}<h2>新增人員</h2>@using (Html.BeginForm()) {    @Html.ValidationSummary(true)    <fieldset>        <legend>新增人員</legend>        <div class="editor-label">            @Html.LabelFor(model => model.Name)        </div>        <div class="editor-field">            @Html.TextBoxFor(model => model.Name)            @Html.ValidationMessageFor(model => model.Name)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Sex)        </div>        <div class="editor-field">            @*@Html.EditorFor(model => model.Sex)*@            @Html.DropDownList("Sex", new[] {new SelectListItem{Value="true",Text=""},           new SelectListItem{Value="false",Text=""}})            @Html.ValidationMessageFor(model => model.Sex)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Brithday)        </div>        <div class="editor-field">            @Html.TextBoxFor(model => model.Brithday)                        @Html.ValidationMessageFor(model => model.Brithday)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Remark)        </div>        <div class="editor-field">            @Html.TextAreaFor(model => model.Remark, new { @rows = 10, cols = "80" })            @Html.ValidationMessageFor(model => model.Remark)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Discriminator)        </div>        <div class="editor-field">            @Html.TextBoxFor(model => model.Discriminator)            @Html.ValidationMessageFor(model => model.Discriminator)        </div>        <p>            <input type="submit" value="新增" />        </p>    </fieldset>}
      Create View  

            (2)編輯Controller和View,先從前臺獲得一個ID進行編輯。 

                      
       [ValidateInput(false)]        public ActionResult Edit(int? id)        {                     var p1 = persons.People.Where(pe => pe.ID == id).FirstOrDefault();            return View(p1);        }        //        // POST: /Person/Edit/5        [HttpPost]        [ValidateInput(false)]        public ActionResult Edit(int? id, string namess, FormCollection collection, int pagesize)        {                        try            {                // TODO: Add update logic here                var p = persons.People.Where(t => t.ID == id).FirstOrDefault();                TryUpdateModel(p, collection);                persons.SaveChanges();                return Content("<script>alert('修改成功!');window.parent.location.href='/Person/Index'</script>");            }            catch            {                return View();            }        }
      Edit Controller                       
@model 無重新整理分頁[email protected]{    ViewBag.Title = "Edit";    Layout = "~/Views/Shared/_Ba.cshtml";}<h2>編輯</h2><script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script><script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>@using (Html.BeginForm()) {    @Html.ValidationSummary(true)    <fieldset>        <legend>人員資訊</legend>        @Html.HiddenFor(model => model.ID)        <div class="editor-label">            @Html.LabelFor(model => model.Name)        </div>        <div class="editor-field">            @Html.TextBoxFor(model => model.Name)            @Html.ValidationMessageFor(model => model.Name)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Sex)        </div>        <div class="editor-field">            @Html.DropDownList("sex", new[]{new SelectListItem{Text="",Value="true"},new SelectListItem{Text="",Value="false"}})            @Html.ValidationMessageFor(model => model.Sex)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Brithday)        </div>        <div class="editor-field">            @Html.TextBoxFor(model => model.Brithday)            @Html.ValidationMessageFor(model => model.Brithday)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Remark)        </div>        <div class="editor-field">            @Html.TextAreaFor(model => model.Remark, new { @rows = 10, cols = "80" })            @Html.ValidationMessageFor(model => model.Remark)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Discriminator)        </div>        <div class="editor-field">            @Html.TextBoxFor(model => model.Discriminator)            @Html.ValidationMessageFor(model => model.Discriminator)        </div>        <p>            <input type="submit" value="儲存" />        </p>    </fieldset>}
      Edit View  

             (3)刪除就不需要View了,在"_fenye"裡使用的是Jquery.Post(),方法,接著刪除對應的該行,使用fadeOut、fadeIn、fadeOut的方式,刪除就可以實現一個閃動效果。

                      
        public ActionResult Delete(int id)        {            try            {                // TODO: Add delete logic here                var p = persons.People.Where(t => t.ID == id).FirstOrDefault();                persons.DeleteObject(p);                persons.SaveChanges();                return Content("OK");            }            catch            {                return View();            }        }
      Delete Controller  

二、總結:

 

        MVC中基本的增刪改查,分頁功能就全部實現了,對於初學者是一份寶貴的資料,如果對您有幫助。那就關注我吧,右下角的“推薦”可別忘了,給更多的MVC+EF初學者參考和學習!

 

      
          附件下載地址:http://files.cnblogs.com/tianxinbest/無重新整理分頁.zip

 

  


<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>           

給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow

這裡寫圖片描述