使用jQuery从实体框架数据库删除记录
问题描述:
我有一个将列出名称的MVC应用程序。 (名称位于实体框架数据库中。)计时器位于列表中的名字旁边,当计时器结束时,名称将从列表中删除,列表中的第二个名称将向上移动,计时器重新开始(这继续直到没有名字被留下)。我需要添加从EF数据库中删除名称的功能。有任何想法吗?使用jQuery从实体框架数据库删除记录
JQuery的
$(document).ready(function() {
startTimer();
function startTimer() {
$('#timer').countdown({
layout: '{mnn} : {snn}', timeSeparator: ':', until: 5, onTick: TimerColorChange, onExpiry: restartTimer
});
}
function restartTimer() {
$('#timer').countdown('destroy');
//we delete the table's Info
var deleteRecord = $('#firstName').parent().remove();
// deleteRecord.deleteRow(); //commented out since this also removes my timer
startTimer();
}
function TimerColorChange(periods) {
var seconds = $.countdown.periodsToSeconds(periods);
if (seconds <= 3) {
$(this).css("color", "red");
} else {
$(this).css("color", "black");
}
}
});
型号代码:
public class UserName
{
public int Id { get; set; }
[Display(Name = "Full Name")]
public string FullName { get; set; }
}
public class UserNameDBContext : DbContext
{
public DbSet<UserName> UserNames { get; set; }
}
检视:
@model IEnumerable<RangeTimer.Models.UserName>
@{
ViewBag.Title = "";
}
<br />
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.FullName)
</th>
<th>
Time Remaining
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td id="firstName">
@Html.DisplayFor(modelItem => item.FullName)
</td>
<td id="timer">
<span id="timer"></span>
</td>
</tr>
}
</table>
控制器:
private UserNameDBContext db = new UserNameDBContext();
// GET: UserNames
public ActionResult Index()
{
return View(db.UserNames.ToList());
}
答
我会给你一个小为例:
1)添加一个方法来删除用户名在你在你的JavaScript控制器
// GET: Delete
public JsonResult DeleteName(string name)
{
//Delete your user from your context here
return Json(true, JsonRequestBehavior.AllowGet);
}
2)调用该函数与一个Ajax请求:
function restartTimer() {
$('#timer').countdown('destroy');
//we delete the table's Info
var deleteRecord = $('#firstName').parent().remove();
// deleteRecord.deleteRow(); //commented out since this also removes my timer
var action ='@Url.Action("DeleteName","Controller")';
$.get(action+"?name="+nameToDelete).done(function(result){
if(result){
// your user is deleted
}
})
startTimer();
}
很多想法,但我不打算为你做所有的研究和调整工作,所以这里有一些想法。 (1)jQuery不能直接修改数据库。 (2)让jQuery调用控制器动作并让控制器动作修改数据库。 –
谢谢你的想法。请放心,我并没有要求你做所有的研究和工作。我研究了这是为什么我张贴在这里谢谢。 – user2448412