【问题标题】:Missing something in "Delete" post method in MVC (EF 4.1)MVC 中的“删除”发布方法中缺少某些内容(EF 4.1)
【发布时间】:2012-02-28 15:51:04
【问题描述】:

按照这个例子..http://msdn.microsoft.com/en-us/data/gg685489

我遇到了删除功能的问题。

[HttpPost]
public ActionResult Delete(int id, Blog blog)
{
    try
    {
        using (var db = new BlogDataEntities())
        {
            //Having issue here.. as soon as the next line is run in debug
            //mode .. it goes to catch.. and returns a view with null values.

            db.Entry(blog).State = System.Data.EntityState.Deleted;
            db.SaveChanges();
        }
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

在我检查“博客”的参数中没有得到需要删除的实际博客模型。所有其他方法都可以正常工作(编辑,删除(获取)..等。 但删除帖子失败。我错过了什么吗?提前感谢您的帮助。

编辑:

查看代码

@model DBFirstMVC.Models.Blog

@{
 ViewBag.Title = "Delete";
 }

  <h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>Blog</legend>

<div class="display-label">Title</div>
<div class="display-field">@Model.Title</div>

<div class="display-label">BloggerName</div>
<div class="display-field">@Model.BloggerName</div>
 </fieldset>
@using (Html.BeginForm()) {
  <p>
    <input type="submit" value="Delete" /> |
    @Html.ActionLink("Back to List", "Index")
  </p>
 }

编辑 2: 视图中的非 Razor 代码:

<% using (Html.BeginForm()) { %>
<p>
    <input type="submit" value="Delete" /> |
    <%: Html.ActionLink("Back to List", "Index") %>
</p>
<% } %>

编辑 3:(我在 aspx 中尝试过)

<% using (Html.BeginForm()) { %>
<p>

    <%=Html.DisplayForModel();%> //Tried Html.EditorForModel also..
    <input type="submit" value="Delete" /> |
    <%: Html.ActionLink("Back to List", "Index") %>
</p>
<% } %>

最终编辑(更正的解决方案)

@model DBFirstMVC.Models.Blog

@{
 ViewBag.Title = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>

@using (Html.BeginForm()) {
 <p>
<fieldset>
<legend>Blog</legend>

<div class="display-label">Title</div>
<div class="display-field">@Model.Title</div>

<div class="display-label">BloggerName</div>
<div class="display-field">@Model.BloggerName</div>

  <input type="submit" value="Delete" /> |
@Html.ActionLink("Back to List", "Index")
</fieldset>
</p>
}

【问题讨论】:

  • 捕获异常,看看是什么问题
  • @ZVenue 我已经用你的新细节更新了我的答案。您没有传递足够的数据来构建您的模型。
  • 请参阅 OP 中的 EDIT2 了解非 razor 语法。如何在非 razor 中编写 EditorForModel ?
  • 仍然无法正常工作,请在 OP 中查看我的新编辑。谢谢
  • 我发布了一个关于在您的代码中为后代分离关注点的答案,但@Dismissile 提出的观点是正确的答案。

标签: asp.net-mvc asp.net-mvc-3 entity-framework entity-framework-4


【解决方案1】:

上下文可能没有您的博客的条目,因为它没有附加到上下文。

您可能需要先检索博客,然后使用Entry 方法将其标记为已删除:

[HttpPost]
public ActionResult Delete(int id, Blog blog)
{
    try
    {
        using (var db = new BlogDataEntities())
        {
            // retrieve the blog from the database
            var realBlog = db.Blogs.Find(blog.Id);

           // nothing to do here, just redirect
           if( realBlog == null )
                return RedirectToAction("Index");

          // since you have the entity just do this instead:
          db.Blogs.Remove(realBlog);
          db.SaveChanges();
        } 

        return RedirectToAction("Index");
    }
    catch( Exception )
    {
        return View();
    }
}

不过,我不太同意将实体用作模型的想法。您应该改用视图模型。

编辑

既然你现在说博客没有被通过,试试这个:

@model Blog

@using ( Html.BeginForm() )
{
    @Html.EditorForModel()

    <input type="submit" value="Delete" />
}

您实际上并未向模型绑定器提供构建模型所需的任何细节。

【讨论】:

  • 我试过你的解决方案..我认为问题出在某个地方..我在这里遗漏了一些非常简单的东西..博客根本没有通过.. public ActionResult Delete(int id, Blog blog )博客在这里是空的.. Delete GET 方法正确地向我显示了完整的博客记录.. 但是当我单击删除按钮时,调用 POST 方法.. 在这里我看到博客没有被传递..它为博客传递了一个空值..
  • @ZVenue 更新了答案。尝试在表单标签中的视图中放入@Html.EditorForModel()。
  • +1 拒绝为达到解决方案。我知道删除视图中一定有问题(因此我的评论要求它)..
  • 你如何用非 razor 语法写这个.. 或 似乎不起作用
  • 虽然它可以工作,但它会给您的应用程序增加不必要的开销。当删除只需要博客文章的id 时,为什么要传递整个Blog 对象?好像向讨厌的蚊子发射导弹。唯一需要传递整个Blog 对象的时间是Create、Read、Update。
【解决方案2】:

是否可以尝试以下方法:

[HttpPost]
public ActionResult Delete(Blog deletedBlog)
{
    try
    {
        using (var db = new BlogDataEntities())
        {
            // get blog entry from db context!!
            Blog blog = db.Blogs.Find(deletedBlog.Id);
            //Having issue here.. as soon as the next line is run in debug
            //mode .. it goes to catch.. and returns a view with null values.

            db.Entry(blog).State = System.Data.EntityState.Deleted;
            db.SaveChanges();
        }
        return RedirectToAction("Index");
    }
    catch(Exception e)
    {
        // should catch more specific exception
        // but catching 'e' should be a start
        return View();
    }
}

[更新] - 从视图中传入您的博客模型,但正如 Dismissile 所说,您应该真正使用视图模型,而不是为此目的使用实体模型。

此外,您应该捕获内部异常消息并检查它以获取更多线索。

【讨论】:

  • 唯一的问题是我已经有一个类似的方法来“获取”删除.. public ActionResult Delete(int id) { using (var db = new BlogDataEntities()) { return View(db .Blogs.Find(id)); } }
  • 啊,当然。那里想得太慢了。您当然需要将视图模型传递回 HttpPost 操作。我会稍微修改我的答案...
  • 同样的事情在这里..请查看我对其他解决方案的评论..我没有正确传递博客..我错过了什么?在这种情况下,deletedBlog 在传递给方法时为空。为什么模型在单击删除按钮时不会传递?
  • 您的 Razor 视图代码在 Delete.cshtml 中是什么样的。在你的问题中弹出它,因为我认为这对我有很大帮助
  • 请参阅 OP 编辑​​。是的,博客模型确实没有被传递..但是编辑视图代码和操作代码的工作方式相同,编辑操作工作正常..它通过了博客模型..如果您查看代码,删除代码非常相似在示例中.. 但博客仍然没有被传递.. 有没有办法强制视图将模型传递给控制器​​...
【解决方案3】:

Delete 操作中的 blog 参数很可能为空,因为您只发布博客的 ID,而不是整个博客对象。我会修改删除操作以仅接受 id(根据 Dismissile 的回答),或者修改删除视图以发布整个博客对象并从操作中删除 id(因为它属于博客对象):

[HttpPost]
public ActionResult Delete(Blog blog)
{
    try
    {
        using (var db = new BlogDataEntities())
        {
            db.Entry(blog).State = System.Data.EntityState.Deleted;
            db.SaveChanges();
        }
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

【讨论】:

  • 该代码没有明确说明其发布ID或博客..它只是一个删除按钮..请参阅OP中的编辑。编辑有类似的代码,并成功通过博客。
  • @ZVenue - 编辑操作接收非空博客模型的原因是视图发布了一个表单,其中包含构造博客对象所需的所有参数。在删除的情况下,唯一传递的参数是 id(来自查询字符串)。
【解决方案4】:

我在几个 cmets 中发布了这个,但我觉得它值得一个单独的答案作为“替代”。

您的控制器应该纤薄,并尽可能遵守single responsibility principle。

博客控制器

public class BlogController : Controller
{
    private BlogService blogService;

    public BlogService()
    {
        blogService = new BlogService();
    }

    [HttpPost]
    public ActionResult Delete(int id)
    {

        // make sure the user has permission to delete before actually deleting

        // now that we know the user has permission
        if (blogService.Delete(id))
        {
            return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }
}

现在您将拥有一个遵循single responsibility principle 的可重用服务层。

博客服务

public class BlogService
{

    private BlogDataEntities dc;

    public BlogService()
    {
        dc = new BlogDataEntities();
    }

    public bool Delete(int Id)
    {
        try
        {
            var blog= (from b in dc.Blogs where Blog.ID == Id select b).First();

           // blog doesn't exist, exit and return false.
           if( blog == null )
                return false;

          // blog exists, remove it
          dc.Blogs.Remove(blog);

          // push the delete to the database
          SaveChanges();

          // it worked, return true.
          return true;
        }
        catch(System.Exception ex)
        {
            // an error happened, handle it and return false.
            return false;
        }
    }

    // I like to keep my `SubmitChanges()` Separate in case I need to 
    // stack up a few processes before hitting the database.
    public void SaveChanges()
    {
        dc.SaveChanges();
    }  
}

【讨论】:

    猜你喜欢
    • 2013-10-16
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多