2016-03-17 37 views
0

我有一個MVC應用程序將列出名稱。這些名稱位於實體框架數據庫中。計時器位於列表中的名字旁邊,當計時器結束時,該名稱將從列表和數據庫中刪除(直到沒有名字被留下)。應用程序首先顯示數據庫中的5個名稱。當第一個名字被刪除時,我很難過,如何將數據庫中的下一個名字追加到表中。MVC在刪除後追加數據庫記錄到表

例如:如果記錄1,2,3,4,5正在顯示並且記錄1被刪除,我需要記錄2,3,4,5,6來顯示。這是我現在的代碼。

Index.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> 

控制器:

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 }); 
     } 


    } 
+0

OK以及如何刷新頁面後更改數據庫都將依賴於服務器和客戶端通信。例如,計時器是JavaScript計時器還是C#計時器? –

+0

計時器代碼位於index.cshtml文件的腳本標記中。它正在使用jquery – user2448412

+0

至少有兩種方式可以刷新數據;最簡單但並非最優雅的方式是在時間結束時簡單地重定向回到同一頁面,但這會導致整個頁面重新加載,而不是一個非常好的UX。另一種方法是使用jQuery從DOM中刪除,該文件包含從db中刪除的用戶的信息,這可以在沒有完全重新加載的情況下完成,但可能會很快發生,以便用戶不會注意到可能需要一些視覺線索發生了...... –

回答

0

下面的變化應該給你所期望的行爲,但是,更新是相當快,所以被刪除的行之間的變化和添加的新行可能會被忽視(但對於加載動畫來說,這是一個簡單的問題)。

控制器:

[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 }); 
} 

Index.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"); 
       } 

      } 
     }); 
+0

我得到這個工作與靜態數據添加新的記錄,但沒有與數據庫中的數據。謝謝您的幫助。 – user2448412