页面
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/Nav.cshtml";
<link href="~/webuploader/CSS/style.css" rel="stylesheet" />
<link href="~/webuploader/CSS/webuploader.css" rel="stylesheet" />
<script src="~/webuploader/WebUploader_MVC.js"></script>
<script src="~/webuploader/JS/webuploader.js"></script>
}
<form data-bind="submit: Search" class="col-lg-12" style="margin-top:10px;">
<div class="col-lg-2"><input type="text" id="StuNameSearch" data-bind="value: StuNameSearch" placeholder="名称|编号|全称" class="form-control"/></div>
<div class="col-lg-2">
<select id="ctype" data-bind="value: ctype" class="form-control">
<option>课程类型</option>
<option>信息</option>
<option>财艺</option>
</select>
</div>
<div class="col-lg-2">
<select id="status" data-bind="value: status" class="form-control">
<option>系部</option>
<option>信息系</option>
<option>财艺系</option>
<option>机电系</option>
</select>
</div>
<button id="Search" type="submit" class="btn btn-primary">查询</button>
</form>
<div class="col-lg-12" style="margin-top:10px;">
<div class="col-lg-1"><button type="button" class="btn btn-primary" style="width:100%" data-bind="click: xianshi">添加</button></div>
<div class="col-lg-1"><button type="button" class="btn btn-primary" style="width:100%" data-bind="click: removeall">多删</button></div>
<div class="col-lg-1"><button type="button" class="btn btn-primary" style="width:100%" data-bind="click: BatchAdd" id="BatchAdd" data-toggle="modal">导入</button></div>
<div class="col-lg-1"><button type="button" class="btn btn-primary" style="width:100%" onclick="Export()">导出</button></div>
</div>
<table id="theader" class="table text-center">
<thead>
<tr>
<th style="width:5%" class="text-center"><input id="selectAll" type="checkbox" onclick="ChoseAll()"></th>
<th style="width:5%" class="text-center">序号</th>
<th style="width:5%" class="text-center">编号</th>
<th style="width:10%" class="text-center">名称</th>
<th style="width:10%" class="text-center">全称</th>
<th style="width:10%" class="text-center">首拼</th>
<th style="width:10%" class="text-center">全拼</th>
<th style="width:10%" class="text-center">类型</th>
<th style="width:10%" class="text-center">系部</th>
<th style="width:10%" class="text-center">图片</th>
<th style="width:20%" class="text-center">操作</th>
</tr>
</thead>
<tbody data-bind="foreach: people">
<tr>
<td><input name="chooseInfo" type="checkbox" data-bind="value: ClassID" onclick=" checkall()"></td>
<td data-bind="text: $index() + 1"></td>
<td data-bind="text: ClassID"></td>
<td data-bind="text: ClassName"></td>
<td data-bind="text: ClassAllName"></td>
<td data-bind="text: FirstSpell"></td>
<td data-bind="text: AllSpell"></td>
<td data-bind="text: Type"></td>
<td data-bind="text: Departments"></td>
<td><img data-bind="attr: { src: Image }" style="width:120px;height:60px;" /></td>
<td>
<button class="btn btn-default" type="button" data-bind="click: $parent.remove">删除</button>
<button class="btn btn-default" type="button" data-bind="click: $parent.Detail">修改</button>
</td>
</tr>
</tbody>
</table>
<div id="nullhide" class="col-lg-12" hidden="hidden">暂无课程</div>
<div class="col-lg-12">
<input id="page" value="1" hidden="hidden" data-bind="value: page"/>
<div class="col-lg-3"><input type="button" id="Fpage" class="btn btn-default" value="首页" data-bind="click: CPage1" /></div>
<div class="col-lg-3"><input type="button" id="Spage" class="btn btn-default" value="上一页" data-bind="click: CPage2" /></div>
<div class="col-lg-3"><input type="button" id="Npage" class="btn btn-default" value="下一页" data-bind="click: CPage3" /></div>
<div class="col-lg-3"><input type="button" id="Lpage" class="btn btn-default" value="末页" data-bind="click: CPage4" /></div>
</div>
<input type="text" name="sexx" id="sexx" hidden="hidden" />
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">添加课程</h4>
</div>
<div class="modal-body" style="height:320px;">
<div class="col-lg-12" style="margin:5px;">
<div class="col-lg-2">编号</div> <div class="col-lg-10"><input type="text" class="form-control" id="txt_ID"></div>
</div>
<div class="col-lg-12">
<label class="col-lg-3 control-label">课程图片<label style="color: red;">*</label></label>
<div class="col-lg-9">
<div id="fileList"></div>
<div class="cp_img_jia" id="filePicker"></div>
<div id="cp_img_jian"></div>
</div>
</div>
<div class="col-lg-12" style="margin:5px;">
<div class="col-lg-6">
<div class="col-lg-3">名称</div><div class="col-lg-9"><input type="text" class="form-control" id="lessname"></div>
</div>
<div class="col-lg-6">
<div class="col-lg-3">全称</div><div class="col-lg-9"><input type="text" class="form-control" id="allname"></div>
</div>
</div>
<div class="col-lg-12" style="margin:5px;">
<div class="col-lg-6">
<div class="col-lg-3">首拼</div><div class="col-lg-9"><input type="text" class="form-control" id="lessspell"></div>
</div>
<div class="col-lg-6">
<div class="col-lg-3">全拼</div><div class="col-lg-9"><input type="text" class="form-control" id="allspell"></div>
</div>
</div>
<div class="col-lg-12" style="margin:5px;">
<div class="col-lg-6">
<div class="col-lg-3">类型</div>
<div class="col-lg-9">
<select id="type" class="form-control">
<option>信息</option>
<option>财艺</option>
</select>
</div>
</div>
<div class="col-lg-6">
<div class="col-lg-3">系部</div>
<div class="col-lg-9">
<select id="depart" class="form-control">
<option>信息系</option>
<option>财艺系</option>
<option>机电系</option>
</select>
</div>
</div>
</div>
<div class="col-lg-12" style="margin: 5px;">
<div class="col-lg-2">简介</div>
<div class="col-lg-10"><textarea class="form-control" rows="5" id="introduce"></textarea></div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="button" id="btn_submit" class="btn btn-primary" data-bind="click: add">保存</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel1">修改课程</h4>
</div>
<div class="modal-body" style="height:320px;">
<div class="col-lg-12" style="margin:5px;">
<div class="col-lg-2">编号</div><div class="col-lg-10"><input type="text" class="form-control" data-bind="value: details1" id="txt_IDEd"></div>
</div>
<div class="col-lg-12" style="margin: 5px;">
<div class="col-lg-6">
<div class="col-lg-3">名称</div><div class="col-lg-9"><input type="text" class="form-control" data-bind="value: details2" id="lessnameEd"></div>
</div>
<div class="col-lg-6">
<div class="col-lg-3">全称</div><div class="col-lg-9"><input type="text" class="form-control" data-bind="value: details3" id="allnameEd"></div>
</div>
</div>
<div class="col-lg-12" style="margin: 5px;">
<div class="col-lg-6">
<div class="col-lg-3">首拼</div><div class="col-lg-9"><input type="text" class="form-control" data-bind="value: details4" id="lessspellEd"></div>
</div>
<div class="col-lg-6">
<div class="col-lg-3">全拼</div><div class="col-lg-9"><input type="text" class="form-control" data-bind="value: details5" id="allspellEd"></div>
</div>
</div>
<div class="col-lg-12" style="margin: 5px;">
<div class="col-lg-6">
<div class="col-lg-3">类型</div>
<div class="col-lg-9">
<select class="form-control" data-bind="value: details6" id="typeEd">
<option>信息</option>
<option>财艺</option>
</select>
</div>
</div>
<div class="col-lg-6">
<div class="col-lg-3">系部</div>
<div class="col-lg-9">
<select class="form-control" data-bind="value: details7" id="departEd">
<option>信息系</option>
<option>财艺系</option>
<option>机电系</option>
</select>
</div>
</div>
</div>
<div class="col-lg-12" style="margin: 5px;">
<div class="col-lg-2">简介</div><div class="col-lg-10"><textarea class="form-control" rows="5" data-bind="value: details8" id="introduceEd"></textarea></div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary" data-bind="click: Save">保存</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="myBatchAdd" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel6">数据数据</h4>
</div>
<div class="modal-body">
<input name="file" type="file" id="file" />
</div>
<div class="modal-footer">
<input id="SaveBatchAdd" data-bind="click: SaveBatchAdd" type="submit" value="批量导入" />
</div>
</div>
</div>
</div>
<script type="text/javascript">
function search() {
$.post('@Url.Action("ClassIndex")', { Name: $('#StuNameSearch').val(), ctype: $('#ctype').val(), status: $('#status').val(), page: parseInt($('#page').val()) }, function (data) {
$('#page').val(data.pagenow);
viewModel.people(data.courselist);
viewModel.pagenow(data.pagenow); viewModel.pagecount(data.pagecount);
});
};
function Export() {
window.location.href = "@Url.Action("Export")";
};
function ChoseAll() {
if ($('#selectAll').is(':checked')) {
$('input[name="chooseInfo"]').each(function () {
$(this).prop("checked", true);
});
}
else {
$('input[name="chooseInfo"]').each(function () {
$(this).prop("checked", false);
});
}
};
function checkall() {
var c = 0;
var chElt = document.getElementById("selectAll");
//2.获取选中状态
var checkedElt = chElt.checked;
console.log(checkedElt)
//3.若checked=true,将所有的复选框选中,checked=false,将所有的复选框取消
var allCheck = document.getElementsByName("chooseInfo");
for (var i = 0; i < allCheck.length; i++) {
//设置复选框的未选中状态
if (allCheck[i].checked != true) {
chElt.checked = false;
}
else {
c++;
}
}
if (c == allCheck.length) {
chElt.checked = true;
}
};
var dataarr;
var DetailID = 0;
var viewModel = {
SaveBatchAdd: ko.observable(""),
StuNameSearch: ko.observable(""), status: ko.observable(""), ctype: ko.observable(""), page: ko.observable(""),
people: ko.observableArray(@Html.Raw(Model.Classlist)),
pagenow: ko.observable(@Html.Raw(Model.pagenow)), pagecount: ko.observable(@Html.Raw(Model.pagecount)),
CPage1: function () {
$('#page').val(1);; search();
},
CPage2: function () {
$('#page').val(viewModel.pagenow() - 1); search();
},
CPage3: function () {
$('#page').val(viewModel.pagenow() + 1); search();
},
CPage4: function () {
$('#page').val(viewModel.pagecount()); search();
},
Search: function () {
var page = this.page;
console.log(page);
$.post('@Url.Action("ClassIndex")', { Name: this.StuNameSearch, ctype: this.ctype, status: this.status, page: this.page.valueOf() }, function (data) {
viewModel.people(data.courselist);
if (data.courselist.length == 0) {
$('#nullhide').attr("style", "display:block;margin:20px;font-size:20px;")
}
});
},
remove: function () {
$.post('@Url.Action("Classmove")', { ID: this.ClassID }, function (data) {
alert("删除成功");
viewModel.people(data);
});
},
removeall: function () {
var ids = new Array();
var names = document.getElementsByName("chooseInfo");
var flag = false;//标记判断是否选中一个
for (var i = 0; i < names.length; i++) {
if (names[i].checked) {
flag = true; ids.push(names[i].value);
}
}
if (!flag) {
alert("请最少选择一项!");
} else {
console.log(ids);
par = { arra: ids.toString() };
$.post('@Url.Action("Classmoveall")', par, function (data) {
alert("删除成功");
viewModel.people(data);
document.getElementById("selectAll").checked = false;
});
}
},
xianshi: function () {
$('#myModal').modal('show');
},
add: function () {
var par = {
id: $('#txt_ID').val(), lessname: $('#lessname').val(), allname: $('#allname').val(), lessspell: $('#lessspell').val(), allspell: $('#allspell').val(),
type: $('#type').val(), depart: $('#depart').val(), introduce: $('#introduce').val()
};
$.get('@Url.Action("Classadd")', par, function (data) {
if (typeof (data) == 'string') {
alert(data);
}
else {
alert("添加成功");
viewModel.people(data);
};
$('#myModal').modal('hide');
});
},
details1: ko.observable(""),details2: ko.observable(""), details3: ko.observable(""),details4: ko.observable(""),
details5: ko.observable(""),details6: ko.observable(""),details7: ko.observable(""),details8: ko.observable(""),
Detail: function () {
$('#myModal1').modal('show');
DetailID = this.ClassID;
$.get('@Url.Action("ClassDetail")', { ID: this.ClassID }, function (data) {
viewModel.details1(data.ClassID); viewModel.details2(data.ClassName); viewModel.details3(data.ClassAllName); viewModel.details4(data.FirstSpell);
viewModel.details5(data.AllSpell); viewModel.details6(data.Type); viewModel.details7(data.Departments); viewModel.details8(data.Introduce);
});
},
Save: function () {
var par = {
id: $('#txt_IDEd').val(), lessname: $('#lessnameEd').val(), allname: $('#allnameEd').val(), lessspell: $('#lessspellEd').val(), allspell: $('#allspellEd').val(),
type: $('#typeEd').val(), depart: $('#departEd').val(), introduce: $('#introduceEd').val()
};
$.get('@Url.Action("ClassDetailSave")', par , function (data) {
if (typeof (data) == 'string') {
alert(data);
}
else {
alert("修改成功");
viewModel.people(data);
};
$('#myModal1').modal('hide');
});
},
BatchAdd: function () {
$('#myBatchAdd').modal('show');
},
SaveBatchAdd: function () {
var fd = new FormData();
fd.append("file", $('#file')[0].files[0]);
$.ajax({
url: '@Url.Action("Import")',
type: "POST",
data: fd,
datatype: 'json',
processData: false,
contentType: false,
success: function (data) {
if (data == "导入成功") {
alert(data);
$('#myBatchAdd').modal('hide');
$('#page').val(1);
search();
}
else {
alert(data);
$('#myBatchAdd').modal('hide');
}
}
})
},
Export: function () {
$.get('@Url.Action("Export")', { }, function (data) {
alert("导出成功");
});
},
};
ko.applyBindings(viewModel);
var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../../";
var $ = jQuery,
$list = $('#fileList'),
ratio = window.devicePixelRatio || 1,
// 缩略图大小
thumbnailWidth = 90 * ratio,
thumbnailHeight = 90 * ratio,
// Web Uploader实例
uploader;
function GetPhotoUrl() {
var photoUrls = "";
$("#fileList img").each(function (i) {
if ($(this).attr("src").indexOf('UpLoad/photos/') > 0) {
photoUrls = photoUrls + $(this).attr("src") + ",";
}
});
for (var i = 0; i < PhotoUrlArray.length; i++) {
photoUrls = photoUrls + PhotoUrlArray[i].filePath;
}
$("#PicUrls").val(photoUrls);
}
//保存从后台返回的图片url
var PhotoUrlArray = new Array();
function PhotoUrl(id, filePath) {
this.id = id;
this.filePath = filePath;
}
// 文件上传成功执行方法
//uploader.on('uploadSuccess', function (file, response) {
// $('#' + file.id).addClass('upload-state-done');
// //将上传的url保存到数组
// PhotoUrlArray.push(new PhotoUrl(response.id, response.filePath));
//});
//执行删除方法
$list.on("click", ".cp_img_jian", function () {
var Id = $(this).parent().attr("id");
//删除该图片
uploader.removeFile(uploader.getFile(Id, true));
for (var i = 0; i < PhotoUrlArray.length; i++) {
if (PhotoUrlArray[i].id == Id) {
PhotoUrlArray.remove(i);
}
}
$(this).parent().remove();
});
$(function () {
uploader = WebUploader.create({
// 选完文件后,是否自动上传。
auto: true,
disableGlobalDnd: true,
// swf文件路径
swf: applicationPath + '/webuploader/Uploader.swf',
// 文件接收服务端。
server: applicationPath + '/Class/UpLoadProcess',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#filePicker',
//只允许选择图片
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
}
});
// 当有文件添加进来的时候
uploader.on('fileQueued', function (file) {
var $li = $(
'<div id="' + file.id + '" class="cp_img">' +
'<img>' +
'<div class="cp_img_jian"></div></div>'
),
$img = $li.find('img');
// $list为容器jQuery实例
$list.append($li);
// 创建缩略图
// 如果为非图片文件,可以不用调用此方法。
// thumbnailWidth x thumbnailHeight 为 100 x 100
uploader.makeThumb(file, function (error, src) {
if (error) {
$img.replaceWith('<span>不能预览</span>');
return;
}
$img.attr('src', src);
}, thumbnailWidth, thumbnailHeight);
});
// 文件上传过程中创建进度条实时显示。
uploader.on('uploadProgress', function (file, percentage) {
var $li = $('#' + file.id),
$percent = $li.find('.progress span');
// 避免重复创建
if (!$percent.length) {
$percent = $('<p class="progress"><span></span></p>')
.appendTo($li)
.find('span');
}
$percent.css('width', percentage * 100 + '%');
});
// 文件上传成功,给item添加成功class, 用样式标记上传成功。
uploader.on('uploadSuccess', function (file, response) {
$('#' + file.id).addClass('upload-state-done');
//将上传的url保存到数组
PhotoUrlArray.push(new PhotoUrl(response.id, response.filePath));
});
// 文件上传失败,显示上传出错。
uploader.on('uploadError', function (file) {
var $li = $('#' + file.id),
$error = $li.find('div.error');
// 避免重复创建
if (!$error.length) {
$error = $('<div class="error"></div>').appendTo($li);
}
$error.text('上传失败');
});
// 完成上传完了,成功或者失败,先删除进度条。
uploader.on('uploadComplete', function (file) {
$('#' + file.id).find('.progress').remove();
});
//所有文件上传完毕
uploader.on("uploadFinished", function () {
});//显示删除按钮
//$(".cp_img").live("mouseover", function () {
// $(this).children(".cp_img_jian").css('display', 'block');
//});
//隐藏删除按钮
//$(".cp_img").live("mouseout", function () {
// $(this).children(".cp_img_jian").css('display', 'none');
//});
//执行删除方法
$list.on("click", ".cp_img_jian", function () {
var Id = $(this).parent().attr("id");
//删除该图片
uploader.removeFile(uploader.getFile(Id, true));
$(this).parent().remove();
});
//显示删除按钮
//$(".cp_img").live("mouseover", function () {
// $(this).children(".cp_img_jian").css('display', 'block');
//});
//$(document).on("mouseover", ".cp_img", function () {
// console.log("进入------");
// $(this).children(".cp_img_jian").css('display', 'block');
//});
});
</script>
后台控制器
using KOTest.Repository.Constaint;
using KOTest.Repository.Entities;
using KOTest.Service.Model;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace KOTest.Controllers
{
public class CourseController : Controller
{
//
// GET: /Class/
DataContent db = new DataContent();
public ActionResult Index()
{
ClassDM bk = new ClassDM();
var list = db.CourseInfo.ToList();
var pageSizeNum = 3;//每页显示多少条
var ItemNum = list.Count();//数据总数
var pageNum = (ItemNum % pageSizeNum) == 0 ? (ItemNum / pageSizeNum) : (ItemNum / pageSizeNum) + 1;//总页数
int pageNumber = 1;
bk.pagecount = pageNum;
bk.pagenow = pageNumber;
bk.Classlist = JsonConvert.SerializeObject(list.OrderBy(x => x.CourseID).Skip((pageNumber - 1) * pageSizeNum).Take(pageSizeNum).ToList());
return View(bk);
}
[HttpPost]
public ActionResult ClassIndex(String Name, String ctype, String status, Int32? page)
{
ClassDM bl = new ClassDM();
var bk = db.CourseInfo.ToList();
if (!String.IsNullOrEmpty(Name))
{
bk = bk.Where(s => s.CourseID.Contains(Name) || s.CourseName.Contains(Name) || s.CourseAllName.Contains(Name)).ToList();
}
if (ctype != "课程类型")
{
bk = bk.Where(s => s.Type.Contains(ctype)).ToList();
}
if (status != "系部")
{
bk = bk.Where(s => s.Departments.Contains(status)).ToList();
}
int dataCount = bk.Count();
bl.pagecount = dataCount % 3 == 0 ? dataCount / 3 : dataCount / 3 + 1;
if (page < 1 || page == null)
{ page = 1; }
if (bl.pagecount < 1)
{ bl.pagecount = 1; }
if (page > bl.pagecount)
{ page = bl.pagecount; }
bl.pagenow = page;
bl.courselist = bk.OrderBy(a => a.CourseID).Skip(3 * page.Value - 3).Take(3).ToList();
return Json(bl);
}
public class UserDM
{
public List<ClassInfo> userlist { get; set; }
public int? pagecount { get; set; }
public int? pagenow { get; set; }
}
//删除
[HttpPost]
public ActionResult Classmove(String ID)
{
CourseInfo bk = db.CourseInfo.Find(ID);
db.CourseInfo.Remove(bk);
db.SaveChanges();
var p = db.CourseInfo.OrderBy(x => x.CourseID).Skip(0).Take(3).ToList();
return Json(p);
}
//多删
[HttpPost]
public ActionResult Classmoveall(Array arra)
{
var str = arra.GetValue(0).ToString();
var ids = str.Split(',');
for (var i = 0; i < ids.Length; i++)
{
var ID = ids.GetValue(i);
CourseInfo bk = db.CourseInfo.Find(ID);
db.CourseInfo.Remove(bk);
db.SaveChanges();
}
var p = db.CourseInfo.OrderBy(x => x.CourseID).Skip(0).Take(3).ToList();
return Json(p);
}
//修改数据
[HttpGet]
public ActionResult ClassDetail(String id)
{
var contactInfo = db.CourseInfo.Where(s => s.CourseID == id).FirstOrDefault();
return Json(contactInfo, JsonRequestBehavior.AllowGet);
}
//修改
[HttpGet]
public ActionResult ClassDetailSave(String id, String lessname, String allname, String lessspell, String allspell, String type, String depart, String introduce)
{
if (id == "")
{ return Json("编号不能为空", JsonRequestBehavior.AllowGet); }
else if (lessname == "")
{ return Json("名称不能为空", JsonRequestBehavior.AllowGet); }
else if (allname == "")
{ return Json("全称不能为空", JsonRequestBehavior.AllowGet); }
else if (lessspell == "")
{ return Json("首拼不能为空", JsonRequestBehavior.AllowGet); }
else if (allspell == "")
{ return Json("全拼不能为空", JsonRequestBehavior.AllowGet); }
else if (type == "")
{ return Json("类型不能为空", JsonRequestBehavior.AllowGet); }
else if (depart == "")
{ return Json("系部不能为空", JsonRequestBehavior.AllowGet); }
else if (introduce == "")
{ return Json("简介不能为空", JsonRequestBehavior.AllowGet); }
else
{
var q = db.CourseInfo.Where(a => a.CourseID == id).ToList();
if (q.Count > 0)
{
return Json("该编号已存在", JsonRequestBehavior.AllowGet);
}
else
{
CourseInfo bk = db.CourseInfo.Find(id);
bk.CourseID = id;
bk.CourseName = lessname;
bk.CourseAllName = allname;
bk.FirstSpell = lessspell;
bk.AllSpell = allspell;
bk.Type = type;
bk.Departments = depart;
bk.Introduce = introduce;
db.SaveChanges();
var p = db.CourseInfo.OrderBy(x => x.CourseID).Skip(0).Take(3).ToList();
return Json(p, JsonRequestBehavior.AllowGet);
}
}
}
//上传图片
public static string filePath1;
public ActionResult UpLoadProcess(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
{
//保存到临时文件夹
string urlPath = "../Upload";
string filePathName = string.Empty;
string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload");
if (Request.Files.Count == 0)
{
return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = "id" });
}
string ex = Path.GetExtension(file.FileName);
filePathName = Guid.NewGuid().ToString("N") + ex;
if (!System.IO.Directory.Exists(localPath))
{
System.IO.Directory.CreateDirectory(localPath);
}
file.SaveAs(Path.Combine(localPath, filePathName));
filePath1 = urlPath + "/" + filePathName;
return Json(new
{
jsonrpc = "2.0",
id = id,
filePath = urlPath + "/" + filePathName//返回一个视图界面可直接使用的url
});
}
//添加
[HttpGet]
public ActionResult Classadd(String id, String lessname, String allname, String lessspell, String allspell, String type, String depart, String introduce)
{
if (id == "")
{ return Json("编号不能为空", JsonRequestBehavior.AllowGet); }
else if (lessname == "")
{ return Json("名称不能为空", JsonRequestBehavior.AllowGet); }
else if (allname == "")
{ return Json("全称不能为空", JsonRequestBehavior.AllowGet); }
else if (lessspell == "")
{ return Json("首拼不能为空", JsonRequestBehavior.AllowGet); }
else if (allspell == "")
{ return Json("全拼不能为空", JsonRequestBehavior.AllowGet); }
else if (type == "")
{ return Json("类型不能为空", JsonRequestBehavior.AllowGet); }
else if (depart == "")
{ return Json("系部不能为空", JsonRequestBehavior.AllowGet); }
else if (introduce == "")
{ return Json("简介不能为空", JsonRequestBehavior.AllowGet); }
else
{
var q = db.CourseInfo.Where(a => a.CourseID == id).ToList();
if (q.Count > 0)
{
return Json("该编号已存在", JsonRequestBehavior.AllowGet);
}
else
{
CourseInfo bk = new CourseInfo();
bk.CourseID = id;
bk.CourseName = lessname;
bk.CourseAllName = allname;
bk.FirstSpell = lessspell;
bk.AllSpell = allspell;
bk.Type = type;
bk.Departments = depart;
bk.Introduce = introduce;
bk.Image = filePath1;
bk.AddTime = DateTime.Now;
db.CourseInfo.Add(bk);
db.SaveChanges();
var p = db.CourseInfo.OrderBy(x => x.CourseID).Skip(0).Take(3).ToList();
return Json(p, JsonRequestBehavior.AllowGet);
}
}
}
//导入
public ActionResult Import(HttpPostedFileBase file)
{
try
{
var fileName = file.FileName;
var filePath = Server.MapPath(string.Format("~/{0}", "Files"));
string path = Path.Combine(filePath, fileName);
file.SaveAs(path);
DataTable excelTable = new DataTable();
excelTable = ImportExcel.GetExcelDataTable(path);
DataTable dbdata = new DataTable();
dbdata.Columns.Add("CourseID");
dbdata.Columns.Add("CourseName");
dbdata.Columns.Add("CourseAllName");
dbdata.Columns.Add("FirstSpell");
dbdata.Columns.Add("AllSpell");
dbdata.Columns.Add("Type");
dbdata.Columns.Add("Departments");
dbdata.Columns.Add("Introduce");
dbdata.Columns.Add("AddTime");
for (int i = 0; i < excelTable.Rows.Count; i++)
{
DataRow dr = excelTable.Rows[i];
DataRow dr_ = dbdata.NewRow();
dr_["CourseID"] = dr["编号"];
dr_["CourseName"] = dr["名称"];
dr_["CourseAllName"] = dr["全称"];
dr_["FirstSpell"] = dr["首拼"];
dr_["AllSpell"] = dr["全拼"];
dr_["Type"] = dr["类型"];
dr_["Departments"] = dr["系部"];
dr_["Introduce"] = dr["简介"];
dr_["AddTime"] = dr["添加时间"];
dbdata.Rows.Add(dr_);
}
RemoveEmpty(dbdata);
string constr = System.Configuration.ConfigurationManager.AppSettings["meixinEntities_"];
SqlBulkCopyByDatatable(constr, "CourseInfo", dbdata);
return Content("导入成功");
}
catch
{
return Content("导入失败");
}
}
public static void SqlBulkCopyByDatatable(string connectionString, string TableName, DataTable dtSelect)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction))
{
try
{
sqlbulkcopy.DestinationTableName = TableName;
sqlbulkcopy.BatchSize = 20000;
sqlbulkcopy.BulkCopyTimeout = 0;//不限时间
for (int i = 0; i < dtSelect.Columns.Count; i++)
{
sqlbulkcopy.ColumnMappings.Add(dtSelect.Columns[i].ColumnName, dtSelect.Columns[i].ColumnName);
}
sqlbulkcopy.WriteToServer(dtSelect);
}
catch (System.Exception ex)
{
throw ex;
}
}
}
}
protected void RemoveEmpty(DataTable dt)
{
List<DataRow> removelist = new List<DataRow>();
for (int i = 0; i < dt.Rows.Count; i++)
{
bool IsNull = true;
for (int j = 0; j < dt.Columns.Count; j++)
{
if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
{
IsNull = false;
}
}
if (IsNull)
{
removelist.Add(dt.Rows[i]);
}
}
for (int i = 0; i < removelist.Count; i++)
{
dt.Rows.Remove(removelist[i]);
}
}
//导出
[HttpGet]
public ActionResult Export()
{
//将查询出来的数据转化为对象列表的格式
var dao = db.CourseInfo.ToList();
//创建工作簿
HSSFWorkbook excelBook = new HSSFWorkbook();
//为工作簿创建工作表并命名
NPOI.SS.UserModel.ISheet sheet1 = excelBook.CreateSheet("课程信息");
//创建表头
NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);//先创建一行用来放表头
//创建7列并赋值
row1.CreateCell(0).SetCellValue("编号");//第0行,第0列
row1.CreateCell(1).SetCellValue("名称");//第0行,第1列
row1.CreateCell(2).SetCellValue("全称");//第0行,第2列
row1.CreateCell(3).SetCellValue("首拼");//第0行,第3列
row1.CreateCell(4).SetCellValue("全拼");//第0行,第4列
row1.CreateCell(5).SetCellValue("类型");//第0行,第5列
row1.CreateCell(6).SetCellValue("系部");//第0行,第6列
//创建数据行
for (int i = 0; i < dao.Count(); i++)
{
//创建行
NPOI.SS.UserModel.IRow rowTemp = sheet1.CreateRow(i + 1);//因为第一行已经被表头占用了,所以要+1
rowTemp.CreateCell(0).SetCellValue(dao[i].CourseID);
rowTemp.CreateCell(1).SetCellValue(dao[i].CourseName);
rowTemp.CreateCell(2).SetCellValue(dao[i].CourseAllName);
rowTemp.CreateCell(3).SetCellValue(dao[i].FirstSpell);
rowTemp.CreateCell(4).SetCellValue(dao[i].AllSpell);
rowTemp.CreateCell(5).SetCellValue(dao[i].Type);
rowTemp.CreateCell(6).SetCellValue(dao[i].Departments);
}
//命名文件名
var fileName = "课程信息" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffff") + ".xls";
//将Excel表格转化为流,输出
//创建文件流
MemoryStream bookStream = new MemoryStream();
//文件写入流(向流中写入字节序列)
excelBook.Write(bookStream);
//输出之前调用Seek(偏移量,游标位置) 把0位置指定为开始位置
bookStream.Seek(0, SeekOrigin.Begin);
return File(bookStream, "application/vnd.ms-excel", fileName);
}
// 登录
[HttpPost]
public ActionResult Login(string name, string password, string yzm_dl)
{
string tishi;
if (name == "")
{
tishi = "请输入用户名!";
return Json(tishi, JsonRequestBehavior.AllowGet);
}
else if (password == "")
{
tishi = "请输入密码!";
return Json(tishi, JsonRequestBehavior.AllowGet);
}
else if (yzm_dl == "")
{
tishi = "请输入验证码!";
return Json(tishi, JsonRequestBehavior.AllowGet);
}
else if (Session["CheckCode"].ToString().ToLower() != yzm_dl)
{
tishi = "请输入正确的验证码!";
return Json(tishi, JsonRequestBehavior.AllowGet);
}
else
{
if (name != null && password != null)
{
ClassDM ul = new ClassDM();
var q = db.UserInfo.Where(s => s.UserName == name && s.PassWord == password).ToList();//查找用户
ul.useralist = q;
if (q.Count <= 0) { }
else
{
ul.UserName = q.FirstOrDefault().UserName;
}
return Json(ul, JsonRequestBehavior.AllowGet);
}
else
{
tishi = "用户不存在!";
return Json(tishi, JsonRequestBehavior.AllowGet);
}
}
}
// 注册
[HttpPost]
public ActionResult register(string name_zc, string password_zc, string rpassword_zc, string yzm_zc)
{
string tishi;
if (name_zc == "")
{
tishi = "请输入用户名!";
return Json(tishi, JsonRequestBehavior.AllowGet);
}
else if (password_zc == "")
{
tishi = "请输入密码!";
return Json(tishi, JsonRequestBehavior.AllowGet);
}
else if (password_zc != rpassword_zc)
{
tishi = "请输入相同的密码!";
return Json(tishi, JsonRequestBehavior.AllowGet);
}
else if (yzm_zc == "")
{
tishi = "请输入验证码!";
return Json(tishi, JsonRequestBehavior.AllowGet);
}
else if (Session["CheckCode"].ToString().ToLower() != yzm_zc)
{
tishi = "请输入正确的验证码!";
return Json(tishi, JsonRequestBehavior.AllowGet);
}
else
{
UserInfo rd = new UserInfo();
rd.UserID = System.DateTime.Now.ToString("yyyyMMddhhmmss");
rd.UserName = name_zc;
rd.PassWord = password_zc;
db.UserInfo.Add(rd);
db.SaveChanges();
return Json(true, JsonRequestBehavior.AllowGet);
}
}
}
}