为什么传递给Delete操作的对象为空?
问题描述:
我有一个基本的ASP.NET MVC 2应用程序。我有添加和编辑行工作得很好,但删除将无法正常工作。 Delete视图在GET上获得正确的记录,但在回发时,传递的参数为空,如CategoryID = 0中的所有空值。因此,没有发现从数据库中删除对象并抛出异常。我怎样才能得到正确的类别传递给HttpPost删除操作?为什么传递给Delete操作的对象为空?
下面是我在控制器中已经有了:
public ActionResult Delete(int id)
{
return View(_categoryRespository.Get(id));
}
[HttpPost]
public ActionResult Delete(Category categoryToDelete)
{
try
{
_categoryRespository.Delete(categoryToDelete);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
这是删除视图,正如我所说的正确地显示在获取数据:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MVCApp.Models.Category>" %>
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>Fields</legend>
<div class="display-label">CategoryID</div>
<div class="display-field"><%: Model.CategoryID %></div>
<div class="display-label">SectionName</div>
<div class="display-field"><%: Model.SectionName %></div>
<div class="display-label">CategoryName</div>
<div class="display-field"><%: Model.CategoryName %></div>
<div class="display-label">Content</div>
<div class="display-field"><%: Model.Content %></div>
</fieldset>
<% using (Html.BeginForm()) { %>
<p>
<input type="submit" value="Delete" /> |
<%: Html.ActionLink("Back to List", "Index") %>
</p>
<% } %>
答
你的表格实际上并不是POST
。您可以使用CategoryID
添加隐藏输入,然后在您的存储库中创建一个静态的Delete
方法,该方法将接受CategoryID作为参数(或者通过CategoryID
实例化一个类别,然后调用您现有的Delete
方法)。
控制器
public ActionResult Delete(int id)
{
return View(_categoryRespository.Get(id));
}
[HttpPost]
public ActionResult Delete(int categoryID)
{
try
{
_categoryRespository.Delete(categoryID);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
查看
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>Fields</legend>
<div class="display-label">CategoryID</div>
<div class="display-field"><%: Model.CategoryID %></div>
<div class="display-label">SectionName</div>
<div class="display-field"><%: Model.SectionName %></div>
<div class="display-label">CategoryName</div>
<div class="display-field"><%: Model.CategoryName %></div>
<div class="display-label">Content</div>
<div class="display-field"><%: Model.Content %></div>
</fieldset>
<% using (Html.BeginForm()) { %>
<p>
<input type="hidden" name="categoryID" value="<%: Model.CategoryID %>" />
<input type="submit" value="Delete" /> |
<%: Html.ActionLink("Back to List", "Index") %>
</p>
<% } %>
感谢红。该解决方案并不完全正确,但它让我走上了正确的轨道。我无法将HttpPost Delete方法更改为仅取int,因为其他Delete方法已具有该签名。所以我改变它为一个int和一个字符串,并为categoryID和categoryName添加隐藏字段。像冠军一样工作:) – witters 2010-06-24 14:08:56
重复签名很好,没有注意到。 – RedFilter 2010-06-24 17:09:01