我有一个MVC应用程序,它将列出名称。名称位于实体框架数据库中。计时器位于列表中的第一个名称旁边,当计时器结束时,名称将从列表和数据库中删除(这将持续到没有名称为止)。应用程序首先显示数据库中的5个名称。我的问题是,当达到最后一条记录时,不是删除记录,而是一遍又一遍地重复记录。我有什么错误的想法?
查看:
@model IEnumerable<RangeTimer.Models.UserName>
<div class="container"></div>
<div class="jumbotron">
<table class="table" id="NameList">
<tr>
<th><span class="glyphicon glyphicon glyphicon-user"></span>
@Html.DisplayNameFor(model => model.FullName)
</th>
<th>
Time Remaining
</th>
</tr>
</table>
<div id="message"></div>
</div>
<br/>
<script language="javascript" type="text/javascript">
$(function () {
var usersList = [];
function init() {
$.ajax({
url: '@Url.Action("GetNames", "UserNames")',
type: "GET",
dataType: "json",
cache: false,
async: true,
success: function (data) {
var row = null,
first = true,
timer = null;
// populate local users list:
usersList = data;
// populate HTML for table:
$.each(usersList, function (index, item) {
row = $('<tr id="row-' + item.Id + '"><td>' + item.FullName + '</td></tr>');
// add a timer to the first row:
if (first) {
$(row).append(getTimer());
first = false;
}
$('#NameList').append(row);
});
},
error: function (error) {
console.log(error);
}
});
}
init();
function restartTimer() {
var deletedElement = null,
nextId = null,
newRow = null,
row = null,
that = this;
// remove the deleted item from local array:
deletedElement = usersList.shift();
// delete record from db on server:
$.ajax({
url: '@Url.Action("Delete", "UserNames")',
type: "POST",
data: ({ id: deletedElement.Id }),
dataType: "json",
cache: false,
async: true,
success: function (data) {
// remove this timer:
$(that).remove();
// add new record to local array:
usersList.push(data);
// add html for row:
newRow = $('<tr id="row-' + data.Id + '"><td>' + data.FullName + '</td></tr>');
console.log(newRow);
$('#NameList').append(newRow);
//remove the html for deleted user:
$('#row-' + deletedElement.Id).remove();
if (usersList.length > 0) {
// get the next item id:
nextId = usersList[0].Id;
// add a timer to the new item:
row = $('#row-' + nextId);
row.append(getTimer());
}
// else {
// $("#message").add("No records to display.")
//}
}
});
}
function getTimer() {
var timer = $('<td></td>');
$(timer).countdown({
layout: '{mnn} : {snn}', timeSeparator: ':', until: 35, onTick: TimerColorChange, onExpiry: restartTimer
});
return timer;
}
function TimerColorChange(periods) {
var seconds = $.countdown.periodsToSeconds(periods);
if (seconds <= 3) {
$(this).css("color", "red");
} else {
$(this).css("color", "black");
}
}
});
</script>
控制器:
public class UserNamesController : Controller
{
private UserNameDBContext db = new UserNameDBContext();
// GET: UserNames
public ActionResult Index()
{
return View(db.UserNames.Take(0).ToList());
}
public ActionResult Admin()
{
return View(db.UserNames.OrderBy(c => c.Id).ToList());
}
// GET: UserNames/Create
public ActionResult Create()
{
return View();
}
// POST: UserNames/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,FullName")] UserName userName)
{
if (ModelState.IsValid)
{
db.UserNames.Add(userName);
db.SaveChanges();
// return RedirectToAction("Create");
return View();
}
return View(userName);
}
// GET: AddUserName
public ActionResult AddUserName()
{
return View();
}
//Post method to add details
[HttpPost]
public ActionResult AddUserName(UserName obj)
{
AddDetails(obj);
TempData["Message"] = obj.FullName + " has been added to the list successfully.";
ModelState.Clear();
return View();
}
private void AddDetails(UserName obj)
{
db.Database.ExecuteSqlCommand("GetAddName @FullName", new SqlParameter("@FullName", obj.FullName));
}
// GET: UserNames/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
UserName userName = db.UserNames.Find(id);
if (userName == null)
{
return HttpNotFound();
}
return View(userName);
}
// POST: UserNames/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,FullName")] UserName userName)
{
if (ModelState.IsValid)
{
db.Entry(userName).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(userName);
}
[HttpGet]
public ActionResult GetNames()
{
return Json(db.UserNames.OrderBy(c=>c.Id).Take(5).ToList(), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Delete(int Id)
{
// TODO: Add delete logic here
UserName userName = db.UserNames.Find(Id);
db.UserNames.Remove(userName);
db.SaveChanges();
//Find the new user
var query = db.UserNames.OrderBy(c => c.Id).Take(5).ToList();
UserName newUserName = query[query.Count - 1];
return Json(newUserName);
}
// GET: UserNames/Delete/5
public ActionResult DeleteFromAdmin(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
UserName userName = db.UserNames.Find(id);
if (userName == null)
{
return HttpNotFound();
}
return View(userName);
}
//// POST: UserNames/Delete/5
[HttpPost, ActionName("DeleteFromAdmin")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int Id, string name)
{
UserName userName = db.UserNames.Find(Id);
db.UserNames.Remove(userName);
db.SaveChanges();
//return Json(newUserName);
return RedirectToAction("Admin");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose()
}
base.Dispose(disposing);
}
}