MVC4 EF5.0 实现异步删除和修改 easyui

1.前台
 
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Mvcfy.Models.yxs_orders>>" %>
 
<!DOCTYPE html>
 
<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="../../Content/PageNavStyle.css" rel="stylesheet" />
    <link href="../../Content/themes/default/easyui.css" rel="stylesheet" />
    <link href="../../Content/themes/icon.css" rel="stylesheet" />
 
 
 
    <script src="../../Scripts/jquery.min.js"></script>
    <script src="../../Scripts/jquery.easyui.min.js"></script>
    <script src="../../Scripts/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript">
        //使用easyui步骤
        //1.将jquery.min.js、jquery.easyui.min.js复制到script中
        //2.将themes文件夹拷贝到项目的Content中,引用default/easyui.css、icon.css
        //3.将locale/easyui-lang-zh_CN.js复制到script,并引用
 
 
 
        $(function () {
            //删除操作
            $(".del").click(function () {
                if (confirm("确认要删除吗?")) {
                    var id = $(this).attr("hid");
                    var link = $(this);
                    $.get("/order/deletebyid""id=" + id, function (data) {
                        if (data == "True") {
                            alert("删除成功!");
                            //fadeOut注意大小写
                            link.parent().parent().fadeOut("slow");
                        } else {
                            alert("删除失败");
                            link.parent().parent().fadeOut("fast");
                            link.parent().parent().fadeIn("fast");
 
                        }
                            
                    });
                   
                }
 
                return false;
            });
            //=======================修改==========================
            //隐藏修改div
            $("#divEdit").css("display""none");
            
            $(".edit").click(function () {
                //修改链接点击后 显示修改div
                $("#divEdit").css("display""block");
                var id = $(this).attr("hid");
                //根据id得到实体的json数据
                $.getJSON("/Order/GetDataById", { id: id }, function (data) {
                    if (data) {
                        //如果data数据不为空
                        $("#txtOrderId").val(data.OrderId);
                        $("#txtUserId").val(data.UserId);
                    }
                });
                $("#divEdit").dialog({
                    title: "修改对话框",
                     500,
                    height: 400,
                    resizable: true,
                    buttons: [{
                        text: '确定',
                        iconCls: 'icon-ok',
                        handler: function () {
                            //弹出的div的确认按钮
                            $.post("/Order/EditData", {OrderId:$("#txtOrderId").val(),UserId:$("#txtUserId").val(),Id:id}, function (data) {
                                if (data == "True") {
                                    alert("修改成功!");
                                    //关闭div
                                    $("#divEdit").dialog("close");
                                } else {
                                    alert("修改失败");
                                }
                            });
                        }
                    },{
                        text:'关闭',
                        handler:function(){
                            $("#divEdit").dialog('close');
                        }
 
                        }]
                });
                
                return false;
            });
        });
 
    </script>
</head>
<body>
    <p>
        <%: Html.ActionLink("Create New""Create"%>
    </p>
    <table>
        <tr>
            <th></th>
            <th>
                <%: Html.DisplayNameFor(model => model.OrderId) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.UserId) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.ReceiverId) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.ShopDate) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.OrderDate) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.ConsigneeRealName) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.ConsigneeName) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.ConsigneePhone) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.ConsigneeProvince) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.ConsigneeAddress) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.ConsigneeZip) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.ConsigneeTel) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.ConsigneeFax) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.ConsigneeEmail) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.WhetherCouAndinte) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.ParvalueAndInte) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.PaymentType) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.Payment) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.Courier) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.TotalPrice) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.FactPrice) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.Invoice) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.Remark) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.OrderStatus) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.PaymentStatus) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.OgisticsStatus) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.SaleUserID) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.SaleUserType) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.BusinessmanID) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.Carriage) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.OrderType) %>
            </th>
            <th>
                <%: Html.DisplayNameFor(model => model.IsOrderNormal) %>
            </th>
            
        </tr>
    
    <% foreach (var item in Model) { %>
        <tr>
            <td>
                <%: Html.ActionLink("修改""Edit"new { id = item.Id }, new {@class="edit",hid=item.Id})%> |
                <%: Html.ActionLink("Details""Details"new { id=item.Id }) %> |
                <%: Html.ActionLink("删除""Delete"new { id = item.Id }, new{@class="del",hid=item.Id })%>
                <%--这里的Action名字写不写都行 在ajax.Get()提交的时候  return false;--%>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.OrderId) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.UserId) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.ReceiverId) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.ShopDate) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.OrderDate) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.ConsigneeRealName) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.ConsigneeName) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.ConsigneePhone) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.ConsigneeProvince) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.ConsigneeAddress) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.ConsigneeZip) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.ConsigneeTel) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.ConsigneeFax) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.ConsigneeEmail) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.WhetherCouAndinte) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.ParvalueAndInte) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.PaymentType) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.Payment) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.Courier) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.TotalPrice) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.FactPrice) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.Invoice) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.Remark) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.OrderStatus) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.PaymentStatus) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.OgisticsStatus) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.SaleUserID) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.SaleUserType) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.BusinessmanID) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.Carriage) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.OrderType) %>
            </td>
            <td>
                <%: Html.DisplayFor(modelItem => item.IsOrderNormal) %>
            </td>
            
        </tr>
    <% } %>
    
    </table>
    <div class="paginator"><%:Html.ShowPageNavigate((int)ViewData["pageIndex"],(int)ViewData["pageSize"],(int)ViewData["total"]) %></div>
 
    <div id="divEdit">
        <table>
            <tr>
                <td>OrderId:</td>
                <td><input type="text" name="txtOrderId" id="txtOrderId" /></td>
            </tr>
            <tr>
                <td>UserId:</td>
                <td><input type="text" name="txtUserId" id="txtUserId" /></td>
            </tr>
        </table>
 
    </div>
</body>
</html>
 
 
 
2.控制器
 
 
using Mvcfy.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace Mvcfy.Controllers
{
    public class OrderController : Controller
    {
        //
        // GET: /Order/
        Entities db = new Entities();
        //分页
        public ActionResult Index()
        {
            var pageIndex = this.Request["pageIndex"] == null ? 1 : int.Parse(this.Request["pageIndex"]);
            var pageSize = this.Request["pageSize"] == null ? 10 : int.Parse(this.Request["pageSize"]);
            var total = db.yxs_orders.Count();
 
            ViewData["pageIndex"] = pageIndex;
            ViewData["pageSize"] = pageSize;
            ViewData["total"] = total;
 
            ViewData.Model = db.yxs_orders.OrderBy<yxs_ordersint>(u => u.Id)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize);
            return View();
        }
 
        //删除
        public ActionResult DeleteById(int id)
        {
            bool flag = false;
            if (id > 0)
            {
                var order=db.yxs_orders.Where<yxs_orders>(u=>u.Id==id).FirstOrDefault();
                db.Entry(order).State = EntityState.Deleted;
                if (db.SaveChanges() > 0)
                {
                    flag = true;
                }
            }
            return Content(flag.ToString());
        }
 
        //修改前加载数据
        public ActionResult GetDataById(int id)
        {
            var order = db.yxs_orders.Where<yxs_orders>(u=>u.Id==id).FirstOrDefault();
            //实体序列化Json数据
            return Json(order,JsonRequestBehavior.AllowGet);
        }
 
        //保存数据
        public ActionResult EditData(yxs_orders order)
        {
            bool flag = false;
            if (order != null)
            { 
                db.Entry(order).State = EntityState.Modified;
                if (db.SaveChanges() > 0)
                {
                    flag = true;
                }
            }
            
            return Content(flag.ToString());
        }
 
        //
        // GET: /Order/Details/5
 
        public ActionResult Details(int id)
        {
            return View();
        }
 
        //
        // GET: /Order/Create
 
        public ActionResult Create()
        {
            return View();
        }
 
        //
        // POST: /Order/Create
 
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
 
        //
        // GET: /Order/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }
 
        //
        // POST: /Order/Edit/5
 
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
 
 
3.Model中分页扩展类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
 
//命名空间用系统命名空间
namespace System.Web.Mvc
{
    public static class MyHtmlHelperExt
    {
        // 传一个字符串过来,我给你封装成一个标签:<span>txt</span> 
        public static string GetLable(this HtmlHelper helper, string txt)
        {
            return string.Format("<span>{0}</span>", txt);
        }
 
 
        // 传一个字符串过来,我给你封装成一个标签:<span>txt</span> 
        public static MvcHtmlString GetMvcHtmlStringLable(this HtmlHelper helper, string txt)
        {
            string str = string.Format("<span>{0}</span>", txt);
            //将上的str 转成   MvcHtmlString
 
            // 创建一个实例:new
            //本类有个静态方法帮我们创建 Create
            //y有个工厂帮我们创建一个实例:HttpApplicationFactory
            //return new MvcHtmlString(str);
 
            //
            return MvcHtmlString.Create(str);
        }
 
        // 传一个字符串过来,我给你封装成一个标签:<span>txt</span> 
        public static HtmlString GetHtmlStringLable(this HtmlHelper helper, string txt)
        {
            string str = string.Format("<span class='laoma'>{0}</span>", txt);
            //将上的str 转成   MvcHtmlString
 
            // 创建一个实例:new
            //本类有个静态方法帮我们创建 Create
            //y有个工厂帮我们创建一个实例:HttpApplicationFactory
            //return new MvcHtmlString(str);
 
            //
            //return MvcHtmlString.Create(str);
 
            return new HtmlString(str);
        }
 
 
 
        public static HtmlString ShowPageNavigate(this HtmlHelper htmlHelper, int currentPage, int pageSize, int totalCount)
        {
            var redirectTo = htmlHelper.ViewContext.RequestContext.HttpContext.Request.Url.AbsolutePath;
            pageSize = pageSize == 0 ? 3 : pageSize;
            var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); //总页数
            var output = new StringBuilder();
            if (totalPages > 1)
            {
                //if (currentPage != 1)
                {//处理首页连接
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex=1&pageSize={1}'>首页</a> ", redirectTo, pageSize);
                }
                if (currentPage > 1)
                {//处理上一页的连接
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>上一页</a> ", redirectTo, currentPage - 1, pageSize);
                }
                else
                {
                    // output.Append("<span class='pageLink'>上一页</span>");
                }
 
                output.Append(" ");
                int currint = 5;
                for (int i = 0; i <= 10; i++)
                {//一共最多显示10个页码,前面5个,后面5个
                    if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages)
                    {
                        if (currint == i)
                        {//当前页处理
                            //output.Append(string.Format("[{0}]", currentPage));
                            output.AppendFormat("<a class='cpb' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage, pageSize, currentPage);
                        }
                        else
                        {//一般页处理
                            output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage + i - currint, pageSize, currentPage + i - currint);
                        }
                    }
                    output.Append(" ");
                }
                if (currentPage < totalPages)
                {//处理下一页的链接
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>下一页</a> ", redirectTo, currentPage + 1, pageSize);
                }
                else
                {
                    //output.Append("<span class='pageLink'>下一页</span>");
                }
                output.Append(" ");
                if (currentPage != totalPages)
                {
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>末页</a> ", redirectTo, totalPages, pageSize);
                }
                output.Append(" ");
            }
            output.AppendFormat("第{0}页 / 共{1}页", currentPage, totalPages);//这个统计加不加都行
 
            return new HtmlString(output.ToString());
        }
    }
}
 
 
 
4.分页样式
 
.paginator
{
    font12px ArialHelveticasans-serif;
    padding10px 20px 10px 0;
    margin0px;
}
 
.paginator a
{
    bordersolid 1px #ccc;
    color#0063dc;
    cursorpointer;
    text-decorationnone;
}
 
.paginator a:visited
{
    padding1px 6px;
    bordersolid 1px #ddd;
    background#fff;
    text-decorationnone;
}
 
.paginator .cpb
{
    border1px solid #F50;
    font-weight700;
    color#F50;
    background-color#ffeee5;
}
 
.paginator a:hover
{
    bordersolid 1px #F50;
    color#f60;
    text-decorationnone;
}
 
.paginator a.paginator a:visited.paginator .cpb.paginator a:hover
{
    floatleft;
    height16px;
    line-height16px;
    min-width10px;
    _width10px;
    margin-right5px;
    text-aligncenter;
    white-spacenowrap;
    font-size12px;
    font-familyArial,SimSun;
    padding0 3px;
}
原文地址:https://www.cnblogs.com/jiayue360/p/3166954.html