2016-11-02 28 views
-2

我有一個標準(CRUD生成)刪除功能如何在控制器中將witin張貼到刪除功能?

// GET: Posts/Delete/5 
     public ActionResult Delete(int? id) 
     { 
      if (id == null) 
      { 
       return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
      } 
      Post post = db.Posts.Find(id); 
      if (post == null) 
      { 
       return HttpNotFound(); 
      } 
      return View(post); 
     } 

     // POST: Posts/Delete/5 
     [HttpPost, ActionName("Delete")] 
     [ValidateAntiForgeryToken] 
     public ActionResult DeleteConfirmed(int id) 
     { 
      Post post = db.Posts.Find(id); 
      db.Posts.Remove(post); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

我想這樣

if (totalVotes <= 5 && voteValue == -1) 
{ 
    Delete(postId); //NOT WORKING 
} 

控制器內調用這個但這讓我刪除GET功能。猜猜我必須在控制器內部發布帖子,但是如何?

回答

0

將刪除代碼移至某個方法,並根據需要從多個方法中調用該方法。

public ActionResult DeleteConfirmed(int id) 
{ 
    DeletePost(id);    
    return RedirectToAction("Index"); 
} 

private void DeletePost(int id) 
{ 
    Post post = db.Posts.Find(id); 
    db.Posts.Remove(post); 
    db.SaveChanges();    
} 

,並在同一個控制器

if (totalVotes <= 5 && voteValue == -1) 
{ 
    DeletePost(postId); 
} 

需要注意的是,該DeletePost方法不返回任何其他方法。所以你的調用方法必須返回一些響應(如果該方法的返回類型不是無效的)

+0

DeleteConfirmed永遠不會被調用。何時使用?沒有[HttpPost]和[ValidateAntiForgeryToken]這樣的刪除功能是否安全? – Xtreme

+0

你不直接調用私人的DeletePost方法?它會從另一個方法調用(例如:DeleteConfirmed操作方法) – Shyju

+0

對不起,但我不明白。你從你的if語句中調用函數DeletePost,但從來沒有DeleteConfirmed。但是你可以從DeleteConfirmed中調用DeletePost。我應該使用DeleteConfirmed(postId)嗎? – Xtreme

相關問題