Mvc音乐商店demo的ajax异步删除功能总结

刚刚从学校出来参加工作,没啥工作经验,所以各位大神们不要嘲笑哈!

来公司后要进行培训,给我们的作业中有一个使用 dapper+mvc+ajax+SQL Server 2008,来实现一个音乐商店的demo。

其他功能都很快实现了,但是那个异步的删除搞了好久,当然了,主要还是因为我不懂JavaScript,不懂jQuery,更不懂ajax。但最后还是勉强实现了。

首先在前台页面加一个属性,用来标记要删除的行的 id:data-id="@item.AlbumId",然后在每行中标记行号: <tr id="Row-@item.AlbumId">

 @foreach (var item in Model) {
<tr id="Row-@item.AlbumId"> <td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.AlbumArtUrl)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.AlbumId }) |
@Html.ActionLink("Details", "Details", new { id=item.AlbumId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.AlbumId }) |
<a href="#" class="ajaxdeletelink" data-id="@item.AlbumId" data-name="@item.Title">ajax删除</a>
</td>
</tr>
}

然后在JavaScript中读取到行号,发送到服务器,进行删除操作,删除前后进行提醒,删除后把删除的那一行用jQuery隐藏掉

 <script type="text/javascript">
//alert("test");
$(function () {
$(".ajaxdeletelink").click(function () {
var albumid = $(this).attr("data-id");
var albumname = $(this).attr("data-name");
if (confirm('确定要删除唱片:' + albumname + '吗?')); else return false;
if (albumid != '') {
$.post("/StoreManager/AjaxDeleteAlbum", { "id": albumid },
function (data) {
if (data.success = true) {
alert("删除成功!")
}
else {
alert("删除失败");
return;
}
$('#Row-' + albumid).fadeOut('slow');//隐藏掉已经删除的那一行
})
}
}
)
})
</script>

就这样,轻轻松松就解决了列表的异步删除功能了哦!!

为了大家参考,在此把后台代码和数据库连接的代码也附上,供大家参考

控制器代码

 using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyMusicStore.Models;
using MyMusicStore.DALs; namespace MyMusicStore.Controllers
{
/// <summary>
/// 管理员操作类
/// </summary>
public class StoreManagerController : Controller
{
private ManagerSQLHelp manager = new ManagerSQLHelp(); //
// GET: /StoreManager/
/// <summary>
/// 获得唱片列表
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
var albums = manager.GetAlbumList();
return View(albums.ToList());
}
/// <summary>
/// 使用ajax异步删除数据
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public bool AjaxDeleteAlbum(int id)
{
Album album = manager.GetAlbumById(id);
bool result=manager.delete(album);
return result;///视图里面还没有实现同时删除掉,需要点击刷新后才显示,记得回来解决这个bug哦
} //
// GET: /StoreManager/Details/5
/// <summary>
/// 通过id获取唱片详情
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult Details(int id)
{ var album = manager.GetAlbumById(id);
album.Artist = manager.GetArtistById(album.ArtistId);
album.Genre = manager.GetGenreById(album.GenreId);
return View(album);
} //
// GET: /StoreManager/Create
/// <summary>
/// 添加唱片
/// </summary>
/// <returns></returns>
public ActionResult Create()
{ var Genres = manager.GetGenreList();
var Artists = manager.GetArtistList();
ViewBag.GenreId = new SelectList(Genres, "GenreId", "Name");
ViewBag.ArtistId = new SelectList(Artists, "ArtistId", "Name");
return View();
} //
// POST: /StoreManager/Create
/// <summary>
/// 添加唱片第二次请求
/// </summary>
/// <param name="album"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Create(Album album)
{
//ManagerSQLHelp manager = new ManagerSQLHelp();
if (ModelState.IsValid)
{
//db.Albums.Add(album);
//db.SaveChanges();
//ManagerSQLHelp manager = new ManagerSQLHelp();
manager.AddAlbum(album);
return RedirectToAction("Index");
}
return View(album);
} //
// GET: /StoreManager/Edit/5
/// <summary>
/// 编辑唱片
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult Edit(int id)
{ Album album = manager.GetAlbumById(id);
album.AlbumId = id;
var Genres = manager.GetGenreList();
var Artists = manager.GetArtistList();
if (album == null)
{
return HttpNotFound();
}
ViewBag.GenreId = new SelectList(Genres, "GenreId", "Name", album.GenreId);//通过id获取名字,显示在下拉框中
ViewBag.ArtistId = new SelectList(Artists, "ArtistId", "Name", album.ArtistId);
return View(album);
} //
// POST: /StoreManager/Edit/5
/// <summary>
/// 编辑唱片提交时
/// </summary>
/// <param name="album"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Edit(Album album)
{ if (ModelState.IsValid)
{ manager.UpdateAlbum(album);
return RedirectToAction("Index");
}
return View(album);
} //
// GET: /StoreManager/Delete/5
/// <summary>
/// 普通方式删除唱片
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult Delete(int id = )
{
//Album album = db.Albums.Find(id);
Album album = manager.GetAlbumById(id);
if (album == null)
{
return HttpNotFound();
}
return View(album);
} //
// POST: /StoreManager/Delete/5
/// <summary>
/// 普通方式删除唱片确认时
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Album album = manager.GetAlbumById(id);
manager.delete(album);
return RedirectToAction("Index");
} protected override void Dispose(bool disposing)
{
//db.Dispose();
base.Dispose(disposing);
}
}
}

数据库连接代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MyMusicStore.Models;
using Dapper; namespace MyMusicStore.DALs
{
/// <summary>
/// 管理员数据库操作类
/// </summary>
public class ManagerSQLHelp
{
/// <summary>
/// 获得唱片列表
/// </summary>
/// <returns></returns>
public List<Album> GetAlbumList()
{
var list = new List<Album>();
try
{
string sql = "select * from Album";
using (var context = DataBaseConnection.GetSqlServerConnection())
{
list = context.Query<Album>(sql).ToList();
context.Dispose();
} }
catch (Exception)
{ throw; }
return list;
}
/// <summary>
/// 获得分类列表
/// </summary>
/// <returns></returns>
public List<Genre> GetGenreList()
{
var list = new List<Genre>();
try
{
string sql = "select * from Genre";
using (var context = DataBaseConnection.GetSqlServerConnection())
{
list = context.Query<Genre>(sql).ToList();
context.Dispose();
} }
catch (Exception)
{ throw; }
return list;
}
/// <summary>
/// 获得艺术家列表
/// </summary>
/// <returns></returns>
public List<Artist> GetArtistList()
{
var list = new List<Artist>();
try
{
string sql = "select * from Artist";
using (var context = DataBaseConnection.GetSqlServerConnection())
{
list = context.Query<Artist>(sql).ToList();
context.Dispose();
} }
catch (Exception)
{ throw; }
return list;
}
/// <summary>
/// 通过唱片id获取唱片信息
/// </summary>
/// <param name="AlbumId"></param>
/// <returns></returns>
public Album GetAlbumById(int AlbumId)
{
var album = new Album();
try
{
string sql = "select * from Album where AlbumId=@AlbumId";
using (var context = DataBaseConnection.GetSqlServerConnection())
{
album = context.Query<Album>(sql, new { AlbumId = AlbumId }).FirstOrDefault();
context.Dispose();
}
}
catch (Exception)
{ throw;
}
return album;
}
/// <summary>
/// 通过id获取分类信息
/// </summary>
/// <param name="GenreId"></param>
/// <returns></returns>
public Genre GetGenreById(int GenreId)
{
var genre = new Genre();
try
{
string sql = "select * from Genre where GenreId=@GenreId";
using (var context = DataBaseConnection.GetSqlServerConnection())
{
genre = context.Query<Genre>(sql, new { GenreId = GenreId }).FirstOrDefault();
context.Dispose();
}
}
catch (Exception)
{ throw;
}
return genre;
}
/// <summary>
/// 通过id获取艺术家信息
/// </summary>
/// <param name="ArtistId"></param>
/// <returns></returns>
public Artist GetArtistById(int ArtistId)
{
var artist = new Artist();
try
{
string sql = "select * from Artist where ArtistId=@ArtistId";
using (var context = DataBaseConnection.GetSqlServerConnection())
{
artist = context.Query<Artist>(sql, new { ArtistId = ArtistId }).FirstOrDefault();
context.Dispose();
}
}
catch (Exception)
{ throw;
}
return artist;
}
/// <summary>
/// 添加唱片
/// </summary>
/// <param name="album"></param>
/// <returns></returns>
public bool AddAlbum(Album album)
{ bool result = false;
try
{
string sql = @"insert into Album (GenreId,ArtistId,Title,Price,AlbumArtUrl)values(@GenreId,@ArtistId,@Title,@Price,@AlbumUrl)";
var paras = new DynamicParameters();
paras.Add("GenreId", album.GenreId);
paras.Add("ArtistId", album.ArtistId);
paras.Add("Title", album.Title);
paras.Add("Price", album.Price);
paras.Add("AlbumUrl", album.AlbumArtUrl);
//var notice = new Notice();
using (var context = DataBaseConnection.GetSqlServerConnection())
{
var affectrow = context.Execute(sql, paras);
result = affectrow == ;
context.Dispose();
} }
catch (Exception)
{ //throw;
}
return result;
}
/// <summary>
/// 更新唱片
/// </summary>
/// <param name="album"></param>
/// <returns></returns>
public bool UpdateAlbum(Album album)
{ bool result = false;
try
{
string sql = @"update Album set GenreId=@GenreId,ArtistId=@ArtistId,Title=@Title,Price=@Price,AlbumArtUrl=@AlbumUrl where AlbumId=@AlbumId";
//insert into Album (GenreId,ArtistId,Title,Price,AlbumArtUrl)values(@GenreId,@ArtistId,@Title,@Price,@AlbumUrl)";
var paras = new DynamicParameters();
paras.Add("AlbumId", album.AlbumId);
paras.Add("GenreId", album.GenreId);
paras.Add("ArtistId", album.ArtistId);
paras.Add("Title", album.Title);
paras.Add("Price", album.Price);
paras.Add("AlbumUrl", album.AlbumArtUrl);
//var notice = new Notice();
using (var context = DataBaseConnection.GetSqlServerConnection())
{
var affectrow = context.Execute(sql, paras);
result = affectrow == ;
context.Dispose();
} }
catch (Exception)
{ //throw;
}
return result;
}
/// <summary>
/// 删除唱片
/// </summary>
/// <param name="album"></param>
/// <returns></returns>
public bool delete(Album album)
{
//var notice = new Notice();
//notice = model;
var result = false;
var albumid = album.AlbumId;
try
{
string sql = "delete from Album where AlbumId=@albumid";
using (var context = DataBaseConnection.GetSqlServerConnection())
{
var affectrow = context.Execute(sql, album);
result = affectrow == ;
context.Dispose();
}
}
catch (Exception)
{ throw;
} return result;
} }
}
上一篇:Fedora 23建立wifi热点(Android手机可用)


下一篇:Thinkphp+Ajax带关键词搜索列表无刷新分页实例