c# - MVC 删除后将数据库记录追加到表中

标签 c# mysql ajax

我有一个将列出姓名的 MVC 应用程序。这些名称位于 Entity Framework 数据库中。列表中的第一个名称旁边有一个计时器,当计时器结束时,该名称将从列表和数据库中删除(这将持续到没有名称留下)。应用程序首先显示数据库中的 5 个姓名。当第一个名称被删除时,我很难将数据库中的下一个名称附加到表中。

例如:如果正在显示记录 1,2,3,4,5,而记录 1 被删除,则我需要显示记录 2,3,4,5,6。这是我现在拥有的代码。

索引.cshtml

@model IEnumerable<RangeTimer.Models.UserName>

@{
      ViewBag.Title = "";
}
<div class="container"></div>
<div class="jumbotron">

<h2>Add Title</h2>

<p>
        @Html.ActionLink("Add Name to list for range time", "AddUserName", new{ target = "_blank" })
    </p>


<hr />


<table class="table" id="NameList">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FullName)
        </th>
        <th>
            Time Remaining
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td id="FullName">

                @Html.DisplayFor(modelItem => item.FullName)
            </td>

            @Html.HiddenFor((modelItem => item.Id))
            <td>

                <span id="timer"></span>

            </td>
        </tr>
    }

</table>

</div>
<br/>
<script language="javascript" type="text/javascript">

$(document).ready(function () {
    startTimer();
    function startTimer() {
        $('#timer').countdown({
            layout: '{mnn} : {snn}', timeSeparator: ':', until: 15, onTick: TimerColorChange, onExpiry: restartTimer
        });
    }


    function restartTimer() {

        var Id = $("#item_Id").val();
        $('#timer').countdown('destroy');

        //we delete the table's Info
        $('#FullName').parent().remove();

        // deleting records from entity framweork database;
        $.ajax({

            url: '@Url.Action("Delete", "UserNames")',
            type: "POST",
            data: ({ Id: Id }),
            dataType: "json",
            cache: false,
            async: true,
            success: function (data) {
                //repopulate list
                $.each(data, function (index, item) {
                    row += "<tr><td>" + item.FullName + "</td></tr>";
                });
                alert(FullName).val();
                $('#NameList').html(row);
                $('#NameList > tbody:last-child').append("<tr><td>"+ $('#FullName').val()+"</td> </tr>");
              // $('#NameList').html(data);
            }

        });


        startTimer();

    }


    function TimerColorChange(periods) {
        var seconds = $.countdown.periodsToSeconds(periods);
        if (seconds <= 3) {
            $(this).css("color", "red");
        } else {
            $(this).css("color", "black");
        }
    }

});

 </script>

Controller :

 public class UserNamesController : Controller
{
    private UserNameDBContext db = new UserNameDBContext();


    // GET: UserNames
    public ActionResult Index()
    {        

        return View(db.UserNames.Take(5).ToList());
    }

    // GET: AddEmployee  
    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));
    }


      [HttpPost]      
    public ActionResult Delete(int Id)
    {
        //try
        //{
            // TODO: Add delete logic here
            UserName userName = db.UserNames.Find(Id);
            db.UserNames.Remove(userName);
            db.SaveChanges();
        //return View(db.UserNames.Take(5).ToList());
            return Json(new { success = true });
        }
        catch
        {
            return Json(new { success = false });
         }


    }

最佳答案

以下更改应该为您提供所需的行为,但是,更新非常快,因此删除的行和添加的新行之间的更改可能会被忽视(但这是使用加载动画进行排序的一个简单问题)。

Controller :

 [HttpGet]
 public ActionResult GetNames()
 {
    return Json(db.UserNames.Take(5).ToList(), JsonRequestBehavior.AllowGet);
 }

 [HttpPost]
 public ActionResult Delete(int id)
 {
     // delete user:
     UserName userName = db.UserNames.Find(id);
     db.UserNames.Remove(userName);
     db.SaveChanges();

     // TODO: find new user here and return as JSON:
     return Json(new UserName { FullName = "User 6", Id = 6 });
 }

索引.cshtml:

<table class="table" id="NameList">
    <tr>
        <th>
            Full Name
        </th>
        <th>
            Time Remaining
        </th>
        <th></th>
    </tr>
</table>

 $(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>');
                            $('#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());
                            }
                        }
                    });
            }

            function getTimer() {
                var timer = $('<td></td>');
                $(timer).countdown({
                    layout: '{mnn} : {snn}', timeSeparator: ':', until: 15, 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");
                }

            }
        });

关于c# - MVC 删除后将数据库记录追加到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36061406/

相关文章:

php - zf2 "join as"语法

jquery - $.ajax() 可以在请求完成之前触发 "success"吗?

php - 转换php字符串数据并用ajax发布?

c# - Resharper 说 OnPropertyChange set member can be private while not true

c# - 来自 Stream : Bug? 的位图

java - 在 Hibernate 3.2 中使用连接池 (c3p0-0.9.1.2) 时出现异常且应用程序无法连接 MySqL 数据库?

Mysql-如何从json文件中获取值

php - 如何避免 Laravel 登录重定向到最新的 AJAX 调用?

c# - 为什么 .net 核心不支持 TransportWithMessageCredential?

c# - UPDATE 语句与 FOREIGN KEY 约束冲突