调用delete方法后如何返回Controller的Index

时间:2014-10-01 10:54:14

标签: c# asp.net-mvc asp.net-mvc-4

我想在删除完成后返回索引,但在索引中我有返回一些Id的类别列表。那么问题是如何使用CategoryId返回Index?

这是索引:

public ActionResult Index([Bind(Prefix = "Id")] int categoryId)
    {
        var category = _db.Categories.Find(categoryId);
        if (category != null)
        {
            return View(category);
        }
        return HttpNotFound();
    }

并删除:

public ActionResult DeleteConfirmed(int id)
    {
        var entry = _db.Entries.Single(r => r.Id == id);

        _db.Entries.Remove(entry);

        _db.SaveChanges();

        return RedirectToAction("Index");
    }

2 个答案:

答案 0 :(得分:1)

您的Index方法参数为categoryId所以

return RedirectToAction("Index", new { categoryId = entry.FK_CategoryId});`

注意,您不需要[Bind(Prefix = "Id")]

public ActionResult Index(int categoryId)

答案 1 :(得分:1)

我找到了解决方案,Delete方法现在看起来像这样:

public ActionResult Delete(int id = 0)
    {
        Entry entry = _db.Entries.Single(r => r.Id == id);
        if (entry == null)
        {
            return HttpNotFound();
        }
        return View(entry);
    }

    //
    // POST: /Restaurant/Delete/5

    [HttpPost, ActionName("Delete")]
    public ActionResult DeleteConfirmed(int id)
    {
        var entryToDelete = _db.Entries.Single(r => r.Id == id);

        _db.Entries.Remove(entryToDelete);

        _db.SaveChanges();

        return RedirectToAction("Index",new { id =  entryToDelete.CategoryId });
    }