最近公司做项目,架构是mvc5 .net core,开发工具是vs2015.
1.前台列表页面
@*
For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
ViewBag.Title = "Index";
Layout = "../Shared/_Layout.cshtml";
}
@model List<InfoManagerDAL.AdvertisementDAL>
<form id="form1">
<div><a href="/Advertise/Addinfo">新增</a></div>
<div>
<h2>广告列表</h2>
<table>
<tr>
<th>编号</th>
<th>图片</th>
<th>作者</th>
<th>添加日期</th>
<th>操作</th>
</tr>
@if (Model == null)
{
<tr>
<td colspan="6">暂无图片</td>
</tr>
}
else
{
foreach (var adver in Model)
{
<tr>
<td>@adver.ID</td>
<td> <img src="@adver.ImageName"></td>
<td>@adver.Creater</td>
<td>@adver.Addtime</td>
<td><a href="/Advertise/Update/@adver.ID">修改</a>
<a href="javascript:void(0);" onclick="del('@adver.ID');">删除</a>
</td>
</tr>
}
}
</table>
</div>
</form>
<script type="text/javascript">
function del(id)
{
$.dialog({
content: '是否确定删除吗?',
ok: function(){
$.ajax({
type: "delete",
url: "/Advertise/delete/" + id,
contentType: "application/json",
dataType: "json",
async: true,
success: function (result) {
if (result.value.isSuccess) {
alert("删除成功!");
setTimeout(function () {location.href = result.value.backurl; }, 500);
} else
alert(result.value.msg);
}
});
return false;
},
cancelVal: '关闭',
cancel: true /*为true等价于function(){}*/
});
}
</script>
B。添加页面
@*
For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
ViewBag.Title = "Index";
Layout = "../Shared/_Layout.cshtml";
}
<form method="post" enctype="multipart/form-data">
<h2>添加广告</h2>
图片:<input type="file" id="files" name="files" multiple /><br/>
链接地址: <input type="text" name="linkurl" id="linkurl" /> <br />
是否置顶:<input type="checkbox" checked="checked" name="Istop" id="Istop"/>
<input type="button"
id="upload"
value="添加" />
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#upload").click(function (evt) {
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = new FormData();
if (files.length == 0) {
alert('请上传照片');
return false;
}
else {
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);//把表单的文件传到后台
}
}
var dz = $("#linkurl").val();
if (dz.length == 0) {
alert('链接地址不能为空');
return false;
}
var files = $("#pic");
if ($.trim(files.val()) == '') {
}
var istop = $("#Istop").prop("checked"); //是否勾选
var choose;
if (istop == true) {
choose = 1;
}
else {
choose = 0;
}
//复值
data.append("LinkAddress", $("#linkurl").val());
data.append("Istop", choose);
$.ajax({
type: "POST",
url: "/Advertise/UploadFilesAjax",
contentType: false,
processData: false,
data:data,
success: function (result) {
if (result.value.isSuccess) {
alert("添加成功!");
location.href = result.value.backurl;
} else
alert(result.value.msg);
},
error: function () {
alert("广告上传失败!");
}
});
});
});
</script>
c.修改页面
@*
For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
ViewBag.Title = "Index";
Layout = "../Shared/_Layout.cshtml";
}
@model InfoManagerDAL.AdvertisementDAL
<form method="post" enctype="multipart/form-data">
<h2>修改广告</h2>
<text>
图片:<input type="file" id="files" name="files" multiple /><br />
链接地址: <input type="text" name="linkurl" id="LinkAddress" value="@Model.LinkAddress"/> <br />
是否置顶: @if (Model.Istop == 1)
{<input type="checkbox" name="asdas" id="LinkAddress" checked="checked" />}
else
{<input type="checkbox" name="Istop" id="Istop" /> }
</text>
<input id="Id" type="hidden" value="@Model.ID" />
<button type="button" id="btnSave">保存</button>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#btnSave").bind("click", function () {
var filesstr = "";
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = new FormData();
if (files.length == 0) {
filesstr = "null";
}
else {
filesstr = "havefile";
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);
}
}
var istop = $("#Istop").prop("checked"); //是否勾选
var choose;
if (istop == true) {
choose = 1;
}
else {
choose = 0;
}
var dz = $("#LinkAddress").val();
if (dz.length == 0) {
alert('链接地址不能为空');
return false;
}
data.append("LinkAddress", $("#LinkAddress").val());
data.append("Istop", choose);
data.append("Isnofile", filesstr);
data.append("ID", $("#Id").val());
$.ajax({
type: "POST",
url: "/Advertise/UpAdvertiseAjax",
contentType: false,
processData: false,
data: data,
success: function (result) {
if (result.value.isSuccess) {
alert("修改成功!");
location.href = result.value.backurl;
} else
alert(result.value.msg);
},
error: function () {
alert("广告上传失败!");
}
});
});
});
</script>
D。后台controller代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using InfoManagerBLL;
using InfoManagerDAL;
using Microsoft.Extensions.Options;
using static InfoManagerBLL.DataBase;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Net.Http.Headers;
using System.IO;
using System.Text;
namespace InfoManagerWebAPI.Controllers
{
//[Route("api/[controller]")]
public class AdvertiseController : Controller
{
private IHostingEnvironment hostingEnv;
public AdvertiseController(IOptions<connStr> con, IHostingEnvironment env)
{
CurrentAdmin.constr = con.Value.connectionString;
this.hostingEnv = env;
}
[HttpGet]
//[HttpGet] 列表页
public IActionResult List()
{
if (!CurrentAdmin.IsLogin) { return Redirect("/home/login"); }
AdvertisementDAL adverdal = new AdvertisementDAL();
AdvertisementBLL adverbll = new AdvertisementBLL();
List<AdvertisementDAL> list = adverbll.GetBannerList(adverdal);
return View(list);
}
//[HttpGet] 新增页
public IActionResult Addinfo()
{
if (!CurrentAdmin.IsLogin) { return Redirect("/home/login"); }
ViewBag.Message = "";
return View();
}
/// <summary>
/// 新增广告页面
/// </summary>
/// <returns></returns>
[HttpPost]
public IActionResult UploadFilesAjax()
{
AdvertisementBLL adb = new InfoManagerBLL.AdvertisementBLL();
AdvertisementDAL adverdal = new AdvertisementDAL();
long size = 0;
var files = Request.Form.Files;
foreach (var file in files)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
var filetype = Path.GetExtension(filename);
filename = hostingEnv.WebRootPath + $@"\{filename}"+DateTime.Now.ToString("MMddHHmmss") + filetype;
size += file.Length;
filename = hostingEnv.WebRootPath + @"\Images\" + DateTime.Now.ToString("MMddHHmmss") + filetype;
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
string link = Request.Form["LinkAddress"];
string Istop = Request.Form["Istop"];
adverdal.LinkAddress = link;
adverdal.Addtime = DateTime.Now;
adverdal.UpdateTime = DateTime.Now;
adverdal.Istop = int.Parse(Istop);
string filenames= "..\\Images\\"+ DateTime.Now.ToString("MMddHHmmss") + filetype;
adverdal.ImageName = filenames;
adverdal.Creater = CurrentAdmin.UserName;
}
Dictionary<string, object> result = new Dictionary<string, object>();
result.Add("isSuccess", adb.AddReturnBool(adverdal));
result.Add("backurl", "/Advertise/List");
result.Add("msg", adb.ErrorMessage);
return new JsonResult(Json(result));
}
/// <summary>
/// 修改页面
/// </summary>
/// <returns></returns>
public IActionResult Update(int ID)
{
if (!CurrentAdmin.IsLogin) { return Redirect("/home/login"); }
AdvertisementDAL adverdal = new AdvertisementDAL();
AdvertisementBLL adverbll = new AdvertisementBLL();
adverdal = adverbll.GetById(ID);
return View(adverdal);
}
[HttpPost]
public IActionResult UpAdvertiseAjax()
{
AdvertisementBLL adb = new InfoManagerBLL.AdvertisementBLL();
AdvertisementDAL adverdal = new AdvertisementDAL();
string adverid=Request.Form["ID"].ToString();
string flags = Request.Form["Isnofile"].ToString();
string link = Request.Form["LinkAddress"];
string Istop = Request.Form["Istop"];
var files = Request.Form.Files;
long size = 0;
adverdal = adb.GetById(int.Parse(adverid));
//没修改照片
if (flags == "null")
{
adverdal.ImageName = adverdal.ImageName;
}
//修改了照片
else {
foreach (var file in files)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
var filetype = Path.GetExtension(filename);
filename = hostingEnv.WebRootPath + $@"\{filename}" + DateTime.Now.ToString("MMddHHmmss") + filetype;
size += file.Length;
filename = hostingEnv.WebRootPath + @"\Images\" + DateTime.Now.ToString("MMddHHmmss") + filetype;
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
string filenames = "..\\Images\\" + DateTime.Now.ToString("MMddHHmmss") + filetype;
adverdal.ImageName = filenames;
}
}
adverdal.LinkAddress = link;
adverdal.Addtime = DateTime.Now;
adverdal.UpdateTime = DateTime.Now;
adverdal.Istop = int.Parse(Istop);
Dictionary<string, object> result = new Dictionary<string, object>();
result.Add("isSuccess", adb.UpdateReturnBool(adverdal));
result.Add("backurl", "/Advertise/List");
result.Add("msg", adb.ErrorMessage);
return new JsonResult(Json(result));
}
[HttpDelete]
public JsonResult Delete(int ID)
{
AdvertisementDAL adverdal = new AdvertisementDAL();
AdvertisementBLL adverbll = new AdvertisementBLL();
Dictionary<string, object> result = new Dictionary<string, object>();
result.Add("isSuccess", adverbll.Del(ID));
result.Add("backurl", "/Advertise/List");
result.Add("msg", adverbll.ErrorMessage);
return new JsonResult(Json(result));
}
}
}
E。页面效果截图