[ASP.net MVC] Html Table資料列的上移、下移,利用Ajax修改DB

[ASP.net MVC] Html Table資料列的上移、下移,利用Ajax修改DB

之前寫過WebForm版:

[ASP.net] GridView、ListView資料列的上移下移(底層sort資料異動的演算法)

,後來因為專案使用ASP.net MVC,所以附上MVC版本

image

 

Model


using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplicationUpDownAjax.Models
{
    public class Product
    {
        public long ProductID { get; set; }

        public string ProductName { get; set; }

        public long Sort { get; set; }
    }
}

Global.asax.cs


using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using MvcApplicationUpDownAjax.Models;

namespace MvcApplicationUpDownAjax
{

   
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : System.Web.HttpApplication
    {
        //假裝這是DB資料
        public static readonly List<Product> products = new List<Product>(){
               new Product(){ ProductID=1, ProductName="Apple", Sort=1},
               new Product(){ ProductID=2, ProductName="Banana", Sort=2},
               new Product(){ ProductID=3, ProductName="Cherry", Sort=3}
             };


        protected void Application_Start()
        {
          


            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

Controller


using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections.Generic;
using MvcApplicationUpDownAjax.Models;

namespace MvcApplicationUpDownAjax.Controllers
{
    public class HomeController : Controller
    {
        
        [HttpGet]
        public ActionResult Index()
        {
           
            return View();
        }

        /// <summary>
        /// 上移,資料愈上Sort愈大
        /// </summary>
        /// <param name="Sort"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult up(long Sort)
        {
            //之後的MvcApplication.products. "OrderByDescending" 會影響大於或小於
           IEnumerable<Product> twoProducts =  MvcApplication.products.OrderBy(m=>m.Sort).Where(m => m.Sort >= Sort).Take(2);
           if (twoProducts!=null && twoProducts.Count()==2)
           {
               Product currentProduct = twoProducts.ToList()[0];
               Product preProduct = twoProducts.ToList()[1];
               //交換Sort
               long temp = preProduct.Sort;
               preProduct.Sort = currentProduct.Sort;
               currentProduct.Sort=temp;
           }


           IEnumerable<Product> products = MvcApplication.products.OrderByDescending(m => m.Sort);
           return View("HtmlTable", products);
        }
        /// <summary>
        /// 下移,資料愈下,Sort愈小
        /// </summary>
        /// <param name="Sort"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult down(long Sort)
        {
            //之後的MvcApplication.products. "OrderByDescending" 會影響大於或小於
            IEnumerable<Product> twoProducts = MvcApplication.products.OrderByDescending(m => m.Sort).Where(m => m.Sort <= Sort).Take(2);
            if (twoProducts != null && twoProducts.Count()==2)
            {
                Product currentProduct = twoProducts.ToList()[0];
                Product nextProduct = twoProducts.ToList()[1];
                //交換Sort
                long temp = nextProduct.Sort;
                nextProduct.Sort = currentProduct.Sort;
                currentProduct.Sort = temp;
            }


            IEnumerable<Product> products = MvcApplication.products.OrderByDescending(m => m.Sort);
            return View("HtmlTable", products);
        }
     
        public ActionResult HtmlTable()
        {
             //從DB撈出資料
            //最新的資料愈往上
            IEnumerable<Product> products = MvcApplication.products.OrderByDescending(m => m.Sort);
            return View("HtmlTable",products);   
    
        }

      
    }
}

 

View

Index.cshtml


<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <script src="~/Scripts/jquery-2.0.3.min.js"></script>
    <title>Index</title>
    <style type="text/css">
        table,td
        {
            border:1px solid black;
        }
    </style>
</head>
<body>
    @*呈現Html Table*@
    <div id="divHtmlTable">
    @Html.Action("HtmlTable","Home")
    </div>

    <script type="text/javascript">
        //上移
        function up(Sort)
        {
            
                $.ajax({
                    url:"@Url.Action("up","Home")",
                    type: "post",
                    cache:false,
                    async:false,
                    data:{Sort:Sort},
                    success:function(result){
                        $("div#divHtmlTable").empty().html(result);
                    }
                
                });
             
        }
        //下移
        function down( Sort) {
             
            $.ajax({
                  url: "@Url.Action("down","Home")",
                  type: "post",
                  async: false,
                  cache:false,
                  data: { Sort: Sort },
                  success: function (result) {
                      $("div#divHtmlTable").empty().html(result);
                  }

              });
            

       
        }

    </script>
</body>
</html>

HtmlTable.cshtml

@using MvcApplicationUpDownAjax.Models
@model IEnumerable<Product>


  <table >
      <tr><td>ProductID</td><td>ProductName</td><td>Sort</td><td>操作</td></tr>
    @foreach (Product p in Model)
    {
        <tr><td>@p.ProductID</td><td>@p.ProductName</td><td>@p.Sort</td>
            <td><input type="button" onclick="up(@p.Sort);" value="上移" />
                 
                <input type="button" onclick="down(@p.Sort);" value="下移" />

            </td>

        </tr>
    }
        </table>

 

 

※2013.8.13補充說明:

發現原本寫法,如果在分頁情況下該頁的最後一列無法下移到下一頁的第一列,已經改了寫法,更新了