分享一個自己寫的MVC+EF “增刪改查” 無刷新分頁程序


一、項目之前得添加幾個組件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 Webdiyer.WebControls.Mvc
@{
    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 Webdiyer.WebControls.Mvc
@{
    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 無刷新分頁.People

@{
    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,FormCollection collection)
        {
            
            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 無刷新分頁.People

@{
    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初學者參考和學習!

      
          附件下載地址: 無刷新分頁項目代碼

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM