C# 如何将控制器中的witin发布到delete函数?
我有一个标准的(CRUD生成的)删除函数C# 如何将控制器中的witin发布到delete函数?,c#,asp.net-mvc,asp.net-mvc-4,controller,crud,C#,Asp.net Mvc,Asp.net Mvc 4,Controller,Crud,我有一个标准的(CRUD生成的)删除函数 // GET: Posts/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Post pos
// 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
}
if(totalvows将删除代码移动到一个方法,并根据需要从多个方法调用该方法
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);
}
if(TotalDeleteConfixed)从未调用。何时使用?在没有[HttpPost]和[ValidateAntiForgeryToken]的情况下执行这样的删除函数是否安全?您不直接调用私有DeletePost方法?它将从另一个方法调用(例如:deleteConfixed操作方法)很抱歉,我不明白。您从if语句调用函数DeletePost,但从未调用deleteConfixed。但是您从deleteConfixed调用DeletePost。我应该使用deleteConfixed(postId)吗?正如我在回答中解释的,您可以从此类中的任何其他方法(包括deleteConfixed)调用它。在问题中,您没有提到if语句的位置!我有一个“标准”删除函数,用于从视图(生成的CRUD)中删除帖子。我还有一个投票函数,如stackoverflow(在同一控制器中),用于根据下一次投票(if语句)删除帖子当然,我可以在if语句中添加delete代码,但从某种意义上说,我已经有了delete post函数,我认为最好重用它。