MVC删除记录,但如何在控制器中编码 [英] MVC Delete record but how to code this in Controller

查看:75
本文介绍了MVC删除记录,但如何在控制器中编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用ASP.Net(C#)的MVC3的初学者,但是我不知道要删除记录的下一种情况.

I'm a beginner of MVC3 with ASP.Net (C#) but I don't get the next situation to delete a record.

我有一个视图,要求用户确认删除项目(记录).作为代码,我有这个来初始化视图:

I have a View that ask the user to confirm delete a item (record). As code I have this to initialize the view:

public ActionResult KeywordsDelete(Guid id)
{
    _db = new BlaContext();
    return _db.SearchTerms.Where(x => x.id.Equals(id)).First();
}

但是,一旦确认,我便有了下一个代码.

But when confirmed, then I have the next code.

[HttpPost]
public ActionResult KeywordsDelete(Guid id)
{
    _db = new BlaContext();
    var term = _db.SearchTerms.Where(x => x.id == id).First();
    _db.SearchTerms.Remove(term);
    _db.SaveChanges();
     return View("Keywords", _db.SearchTerms.ToList());
 }

无法构建,因为此方法的签名已经存在(相同的参数和方法名称).

Building is not possible because the signature of this method is already exists (same parameters and method name).

因此,在这种情况下,我不知道如何删除记录.该视图是使用默认的脚手架模板(删除)创建的.

So I don't get how to delete a record in this situation. The view is created with a default Scaffold template (delete).

推荐答案

您可以为post函数提供另一个附加参数

You can give your post function another additional parameter

[HttpPost]
public ActionResult KeywordsDelete(Guid id, FormCollection collection)
{
    _db = new BlaContext();
    var term = _db.SearchTerms.Where(x => x.id == id).First();
    _db.SearchTerms.Remove(term);
    _db.SaveChanges();
     return View("Keywords", _db.SearchTerms.ToList());
 }

但是,我认为您的GET Action还应该返回一个View而不是一个数据对象.

But your GET Action should also return a View not a data object, I think.

public ActionResult KeywordsDelete(Guid id)
{
    _db = new BlaContext();
    return View(_db.SearchTerms.Where(x => x.id.Equals(id)).First());
}

这篇关于MVC删除记录,但如何在控制器中编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆