asp.net中ashx後臺接口獲取Layui前臺ajax傳送過來的參數

後臺代碼:

//可以獲取任何方式
string photoId = context.Request.Params["photoid"];
 //POST方式傳參
string photoId = context.Request.Form["photoid"];
 //GET方式傳參
string photoId = context.Request.QueryString["photoid"];

完整後臺代碼
ApiEditPhoto .ashx文件代碼如下

<%@ WebHandler Language="C#" Class="ApiEditPhoto" %>

using System;
using System.Web;
using MyBlog.BLL;
using Newtonsoft.Json.Linq;
using System.IO;
public class ApiEditPhoto : IHttpHandler
{
    AlbumService albumService = new AlbumService();

    public void ProcessRequest(HttpContext context)
    {

        context.Response.ContentType = "application/json";
        string photoId = context.Request.Params["photoid"];
        string photoName = context.Request.Params["photoname"];
        bool flag=albumService.updatePhoto(int.Parse(photoId),photoName);
        JObject jo;
        if(flag==true)
        {
            jo = new JObject(new JProperty("msg", "修改成功"));
        }
        else
        {
            jo = new JObject(new JProperty("msg", "修改失敗"));

        }
        context.Response.Write(jo);

    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

ApiGetPhoto.ashx文件代碼如下

<%@ WebHandler Language="C#" Class="ApiGetPhoto" %>

using System;
using System.Web;
using System.IO;
using System.Data;
using System.Text;
using Newtonsoft.Json;
using MyBlog.BLL;
using MyBlog.DAL;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
//獲得所有photo表的信息
public class ApiGetPhoto : IHttpHandler
{
    AlbumService albumService = new AlbumService();

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        string userid = "2";
        List<photo> photoList = albumService.GetAllPhoto(int.Parse(userid));
        string counts = photoList.Count.ToString();
        //重點掌握json對象,注意引入Newtonsoft.Json.Linq和System.Collections.Generic
        //注意layui中table返回數據的json格式如下,如果是自己獨有的json格式,需要在
        //table.render中添加parseData字段,詳見官方文檔
        JObject res = new JObject();
        res.Add(new JProperty("code", 0));
        res.Add(new JProperty("msg", ""));
        res.Add(new JProperty("count", counts));
        JArray photos = new JArray();
        foreach (var item in photoList)
        {
            JObject p = new JObject();
            p.Add(new JProperty("photoId", item.photoId));
            p.Add(new JProperty("photoName", item.photoName));
            p.Add(new JProperty("photoUrl", item.photoUrl));
            p.Add(new JProperty("photoTime", item.photoTime));
            photos.Add(p);
        }
        res.Add(new JProperty("data", photos));
        context.Response.Write(res);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

ApiAddPhoto.ashx文件代碼如下

<%@ WebHandler Language="C#" Class="ApiAddPhoto" %>

using System;
using System.Web;
using System.IO;
using System.Data;
using System.Text;
using Newtonsoft.Json;
using MyBlog.BLL;
using Newtonsoft.Json.Linq;
public class ApiAddPhoto : IHttpHandler
{

    AlbumService albumService=new AlbumService();
    public void ProcessRequest(HttpContext context)
    {

        context.Response.ContentType = "application/json";
        string savePath = HttpContext.Current.Server.MapPath("../UploadFiles/");
        if (!System.IO.Directory.Exists(savePath))
        {
            System.IO.Directory.CreateDirectory(savePath);
        }
        HttpFileCollection hfc = context.Request.Files;
        if (hfc.Count > 0)
        {
            HttpPostedFile hpf = context.Request.Files[0];
            if (hpf.ContentLength > 0)
            {
                string fileName = Path.GetFileName(hpf.FileName);
                savePath = savePath + "\\" + fileName;
                hpf.SaveAs(savePath);
                string path = string.Format("UploadFiles/{0}", fileName);
                //法一
                //string json = "{\"fileName\":\"" + path + "\"}";
                //JObject jo = (JObject)JsonConvert.DeserializeObject(json);

                //法二
                JObject jObject=new JObject(new JProperty("fileName",path)) ;
                context.Response.Write(jObject);
                //獲取當前時間
                DateTime dateTime = DateTime.Now.ToLocalTime();
                //插入數據庫
                albumService.insertPhoto(2, fileName, path, dateTime);

            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

ApiDeletePhoto.ashx文件代碼如下

<%@ WebHandler Language="C#" Class="ApiDeletePhoto" %>

using System;
using System.Web;
using MyBlog.BLL;
using Newtonsoft.Json.Linq;
using System.IO;
public class ApiDeletePhoto : IHttpHandler
{
    AlbumService albumService = new AlbumService();

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        
        string photoId = context.Request.Form["photoid"];
        string url = albumService.delPhoto(int.Parse(photoId));
        JObject jo;
        if (url != null)
        {//成功刪除圖片
            string savePath = HttpContext.Current.Server.MapPath("../" + url);
            File.Delete(savePath);
            jo = new JObject(new JProperty("msg", "刪除成功"));
        }
        else
        {
            jo = new JObject(new JProperty("msg", "刪除失敗"));
        }
        context.Response.Write(jo);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

前臺完整代碼

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyAlbum.aspx.cs" Inherits="MyAlbum" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <link href="Contents/css/layui.css" rel="stylesheet" />
</head>
<body>
    <table class="layui-hide" id="photoTable" lay-filter="test"></table>

    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="getCheckData">獲取選中行數據</button>
            <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">獲取選中數目</button>
            <button class="layui-btn layui-btn-sm" lay-event="isAll">驗證是否全選</button>
        </div>
    </script>

    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">編輯</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除</a>
    </script>
    <script src="Contents/layui.js"></script>

    <script>
        layui.use(['table', 'jquery'], function () {
            var table = layui.table;
            var $ = layui.jquery;
            table.render({
                elem: '#photoTable'
                , url: '/Comm/ApiGetPhoto.ashx'
                , toolbar: '#toolbarDemo' //開啓頭部工具欄,併爲其綁定左側模板,指向自定義工具欄模板選擇器
                , defaultToolbar: ['filter', 'exports', 'print', { //自定義頭部工具欄右側圖標。如無需自定義,去除該參數即可
                    title: '提示'
                    , layEvent: 'LAYTABLE_TIPS'
                    , icon: 'layui-icon-tips'
                }]
                , title: '用戶數據表'
                , cols: [[
                    { type: 'checkbox', fixed: 'left' }
                    , { field: 'photoId', title: '照片ID', width: 120, fixed: 'left', unresize: true, sort: true }
                    , { field: 'photoName', title: '照片名', width: 120 }
                    , {
                        field: 'photoUrl', title: '照片地址', width: 200, templet: function (res) {
                            return '<em>' + res.photoUrl + '</em>'
                        }
                    }
                    , { field: 'photoTime', title: '上傳時間', width: 180 }
                    , { fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150 }
                ]]
                , page: true
            });

            //頭工具欄事件
            table.on('toolbar(test)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id);
                switch (obj.event) {
                    case 'getCheckData':
                        var data = checkStatus.data;
                        layer.alert(JSON.stringify(data));
                        break;
                    case 'getCheckLength':
                        var data = checkStatus.data;
                        layer.msg('選中了:' + data.length + ' 個');
                        break;
                    case 'isAll':
                        layer.msg(checkStatus.isAll ? '全選' : '未全選');
                        break;

                    //自定義頭工具欄右側圖標 - 提示
                    case 'LAYTABLE_TIPS':
                        layer.alert('此表格是用於照片管理');
                        break;
                };
            });

            //監聽行工具事件
            table.on('tool(test)', function (obj) {
                var data = obj.data;
                //console.log(obj)
                if (obj.event === 'del') {
                    layer.confirm('真的刪除行麼', function (index) {
                        $.ajax({
                            type: "post",
                            async: true,
                            url: "/Comm/ApiDeletePhoto.ashx",
                            data: { photoid: data.photoId },
                            success: function (res) {
                                console.log(res);
                                obj.del();
                                //關閉彈出層
                                layer.close(index);
                            }
                        })

                    });
                } else if (obj.event === 'edit') {
                    layer.prompt({
                        formType: 2
                        , title: "編輯照片名"
                        , value: data.photoName
                    }, function (value, index) {
                        $.ajax({
                            type: "post",
                            async: true,
                            url: "/Comm/ApiEditPhoto.ashx",
                            data: { photoid: data.photoId, photoname: value },
                            success: function (res) {
                                console.log(res);
                            }
                        })
                        obj.update({
                            photoName: value
                        });
                        layer.close(index);
                    });
                }
            });
        });
    </script>
</body>
</html>

BLL層服務操作類AlbumService.cs代碼如下,MyBlogDataContext 爲linq to sql類,是由數據庫文件直接轉換而來

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyBlog.DAL;

namespace MyBlog.BLL
{
    
    public class AlbumService
    {
        MyBlogDataContext db = new MyBlogDataContext();
        //插入圖片
        public void insertPhoto(int _userId,string _photoName,string _photoUrl,DateTime _dateTime)
        {
            photo photoItem = new photo
            {
                userId = _userId,
                photoName = _photoName,
                photoUrl = _photoUrl,
                photoTime=_dateTime
            };
            db.photo.InsertOnSubmit(photoItem);
            db.SubmitChanges();
        }

        public List<photo> GetAllPhoto(int _userId)
        {
            List<photo> photoList = new List<photo>();

            var x=from r in db.photo
                  where r.userId==_userId 
                  select r ;
            photoList = x.ToList();
            return photoList; 
        }

        public string delPhoto(int _photoId)
        {
            var x = from r in db.photo
                    where r.photoId == _photoId
                    select r;
            string pUrl=null;
            foreach (var item in x)
            {
                pUrl = item.photoUrl;
            }
            db.photo.DeleteAllOnSubmit(x);
            db.SubmitChanges();
            return pUrl;//返回被刪除圖片的url,從而在服務器上對該圖片進行刪除
        }

        public bool updatePhoto(int _photoId,string _photoName)
        {
            bool flag = false;
            var x = from r in db.photo
                    where r.photoId == _photoId
                    select r;
            if(x!=null)
            {
                foreach (var item in x)
                {
                    item.photoName = _photoName;
                    flag = true;
                }
            }
            db.SubmitChanges();
            return flag;
        }

    }

    
}

效果圖如下
在這裏插入圖片描述

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章