.net Core mvc开发

来源:互联网 发布:配电箱计算软件 编辑:程序博客网 时间:2024/05/19 20:42
@*
    For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewBag.Title = "拍卖会列表";
    Layout = null;
}


<!doctype html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>518大学生创业拍卖会</title>

    <link href="~/auctionPc/css/auction_zk.css" rel="stylesheet" />
    <link href="~/auctionPc/css/base.css" rel="stylesheet" />
    <link href="~/auctionPc/css/font-awesome.min.css" rel="stylesheet" />
    <script src="~/js/jquery-2.2.0.min.js"></script>
    <script src="~/js/lhgdialog/lhgcore.lhgdialog.min.js"></script>
    <script src="~/js/jquery-ui.min.js"></script>
    <link href="~/js/jquery-ui.min.css" rel="stylesheet" />
    <link href="~/sidebarpc/css/sidebar_style.css" rel="stylesheet" />
</head>
<body>

    <form method="post" enctype="multipart/form-data">
        <a id="sids"></a>    
        <input type="button"  class="huge_btn_blue" id="toexcel"  value="导出Excel">
        <input type="text" class="ss" id="txtSreach" placeholder="请输入名称" />
        <input type="button" class="ss-btn" id="btnSreach" value="搜 索多行" />
        <input type="button" class="ss-btn" id="btnSreach2" value="搜 索1行" />
       

        <div id="jg">


        </div>
        <script>
            //查询多行数据
            $("#btnSreach").bind("click", function () {
                var html = "";
                var s = $("#txtSreach").val();         
                var data = new FormData();
                data.append("newyhm", s);
                $.ajax({
                    url: '/test0703/GetMeet',
                    type: 'POST',
                    contentType: false,
                    processData: false,
                    data: data,
                    success: function (context) {

                        $("#jg").html("");
                        var k = context.replace("[", "").replace("]", "");
                        if (context.indexOf("Username") < 0) {
                            $("#jg").html("<b>没查到数据</b>");
                        }
                        else {
                            var userdetail = eval(context);
                            //方法一
                            $.each(userdetail, function (i, item) {
                             var htmls = "用户名:" + item.Username + " 名称:" + item.meetname + " ";
                             $("#jg").append(htmls);
                               });
                            //方法二
                            //for (var i = 0; i < userdetail.length; i++) {              
                            //  html += "用户名:" + userdetail[i].Username + " 名称:" + userdetail[i].meetname + "";                      
                            //}
                            //$("#jg").html(html);
                         }                     
                     }                
                });
            });
            //查询1条数据
            $("#btnSreach2").bind("click", function () {
                var html = "";
                var s = $("#txtSreach").val();
                var data = new FormData();
                data.append("pids", s);
                $.ajax({
                    url: '/test0703/GetDetail',
                    type: 'post',
                    contentType: false,
                    processData: false,
                    data: data,               
                    success: function (mm) {                                
                       if (mm.indexOf("ProductName") < 0) {
                          
                           $("#jg").html("<b>没查到数据</b>");
                       }
                       else {
                           //方法一
                          var str2 = JSON.parse(mm);
                           //$("#jg").html("产品名称 :" + str2.ProductName + " + 描述:" + str2.Description);

                           //方法二
                           //var datas = eval("(" + mm + ")");
                           //$("#jg").html("用户名 :" + datas.ProductName + "描述 :" + datas.Description + " ");

                           //方法三
                           $("#jg").html("用户名 :" + str2["ProductName"] + " + 描述 " +str2["Description"]);                     
                        }                    
                    }

                });
            });

            //导出excel
            $("#toexcel").bind("click", function () {
               
                //location.href = "/test0703/Export";            
                var data = new FormData();
                $.ajax({
                    type: "POST",
                    url: "/test0703/Export",
                    contentType: false,
                    processData: false,
                    data: data,
                    success: function (result) {                      
                        if (result.value.isSuccess) {
                            alert(result.value.v);
                            alert('成功');
                            $("#sids").text(result.value.sname);
                            $('#sids').attr("href",result.value.v);                       
                        }
                    },
                    error: function () {
                        alert("失败!");
                    }
                });

            });
        </script>  
        </form>



        </body>

</html>


controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AuctionManagerBLL;
using AuctionManagerDAL;
using Microsoft.Extensions.Options;
using static AuctionManagerBLL.DataBase;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Net.Http.Headers;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Http;
using System.Data;
using System.Threading;
using OfficeOpenXml;

namespace AuctionManager.Controllers
{
    //[Route("api/[controller]")]
    public class test0703Controller : Controller
    {
        private IHostingEnvironment hostingEnv;

        private readonly IOptions<connStr> con;

        private string constr;
        private string admin;
        public test0703Controller(IOptions<connStr> con, IOptions<Admin> admin, IOptions<usercenterStr> usercenterStr, IHostingEnvironment env)
        {
            this.con = con;
            CurrentAdmin.constr = this.constr = con.Value.connectionString;
            CurrentAdmin.usercenterStr = usercenterStr.Value;
            this.hostingEnv = env;
            this.admin = admin.Value.adminStrstring;
        }
        public IActionResult index(int id)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            RoominfoBLL roombll = new RoominfoBLL();
            RoominfoDAL roomdal = new RoominfoDAL();
            roomdal = roombll.GetById(22);
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(roomdal).Replace("[", "").Replace("]", "");
            ViewBag.str = json;
            return View();
        }



        [HttpPost]
        public JsonResult GetDetail()
        {
            try
            {
                ProductinfoDAL prodal = new ProductinfoDAL();
                ProductinfoBLL probll = new ProductinfoBLL();
                string yh = Request.Form["pids"].ToString();
                prodal = probll.GetById(int.Parse(yh));
                string result = "";
                if (prodal != null)
                {
                    result = Newtonsoft.Json.JsonConvert.SerializeObject(prodal);

                    ViewBag.strnew = result;
                    return Json(result);

                }
                else
                {

                    return Json("[{'msg':'fail'}]");
                }
            }
            catch
            {
                return Json("[{'msg':'fail'}]");
            }
        }
        [HttpPost]
        public JsonResult GetMeet()
        {
            try
            {
                UserpriceDAL usepricedal = new UserpriceDAL();
                UserpriceBLL userpricebll = new UserpriceBLL();
                ProductinfoDAL prodal = new ProductinfoDAL();
                ProductinfoBLL probll = new ProductinfoBLL();
                string yh = Request.Form["newyhm"].ToString();
                usepricedal.Username = yh;
                List<UserpriceDAL> list = userpricebll.GetUserPriceList(usepricedal, null);
                string result = Newtonsoft.Json.JsonConvert.SerializeObject(list.Select(
                   t => new
                   {
                       Username = t.Username,
                       Price = t.Price,
                       proname = ProductinfoBLL.GetProName(int.Parse(t.ProductID.ToString())),
                       meetname = ProductinfoBLL.GetMeetName(int.Parse(t.MeetId.ToString())),
                       Addtime =
                       ((DateTime)t.Addtime).ToString("yyyy-MM-dd HH:mm:ss"),
                       State = t.State,
                       Isdelete = t.Isdelete,
                   }));
                if (result != "[]")
                {
                    return Json(result);
                }
                else
                {
                    return Json("[{'msg':'fail'}]");
                }
            }
            catch (Exception e)
            {
                return Json("[{'msg':'fail','error':'" + e.ToString() + "'}]");
                throw e;
            }
        }
        [HttpPost]
        public IActionResult Export()
        {
            //string sWebRootFolder = _hostingEnvironment.WebRootPath;
            //string sFileName = $"{Guid.NewGuid()}.xlsx";
            string sWebRootFolder = hostingEnv.WebRootPath + "/Upload/";
            string sFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx";
            FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
            using (ExcelPackage package = new ExcelPackage(file))
            {
                // 添加worksheet
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("aspnetcore");
                ////添加头
                //worksheet.Cells[1, 1].Value = "ID";
                //worksheet.Cells[1, 2].Value = "Name";
                //worksheet.Cells[1, 3].Value = "Url";
                ////添加值
                //worksheet.Cells[2,1].Value = 1000;
                //worksheet.Cells[2,2].Value = "LineZero";
                //worksheet.Cells[2,3].Value = "http://www.cnblogs.com/linezero/";
                //worksheet.Cells[3,1].Value = 1001;
                //worksheet.Cells[3,2].Value = "LineZero GitHub";
                //worksheet.Cells[3,3].Value = "https://github.com/linezero";
                //worksheet.Cells[3,3].Style.Font.Bold = true;
                MeetinfoBLL meetbll = new MeetinfoBLL();
                MeetinfoDal meetdal = new MeetinfoDal();
                List<MeetinfoDal> list = meetbll.GetMeetList(meetdal, null);
                ////添加头
                worksheet.Cells[1, 1].Value = "编号";
                worksheet.Cells[1, 2].Value = "拍卖会名称";
                worksheet.Cells[1, 3].Value = "开始时间";
                worksheet.Cells[1, 4].Value = "结束时间";
                worksheet.Cells[1, 5].Value = "创建人";
                for (int i=0;i<list.Count;i++) {              
                    ////添加值
                    worksheet.Cells[i+2, 1].Value = list[i].Id;
                    worksheet.Cells[i+2, 2].Value = list[i].MeetName;
                    worksheet.Cells[i + 2, 3].Value = Convert.ToDateTime(list[i].BeginTime).ToString("yyyy-MM-dd HH:mm:ss");
                    worksheet.Cells[i+2, 4].Value = Convert.ToDateTime(list[i].Endtime).ToString("yyyy-MM-dd HH:mm:ss");
                    worksheet.Cells[i+2, 5].Value = list[i].Creater;
                }
                package.Save();
            }

            HostString host = AuctionManagerBLL.HttpContext.Current.Request.Host;
            string paths = "http://" + host + "/Upload/"+ sFileName;
            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("isSuccess", true);
            result.Add("sname", sFileName);
            result.Add("v", paths);
            result.Add("backurl", "/test0703/index");
            result.Add("msg", "成功");
            return new JsonResult(Json(result));
            //return File(sFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }
    }
}








原创粉丝点击