我有一个基本的ASP.NET MVC 2应用程序。我添加和编辑行工作正常,但删除将无法正常工作。删除视图在GET上获取正确的记录,但在回发时,传递的参数为空,如在CategoryID = 0中,所有空值。因此,没有发现从数据库中删除任何对象并抛出异常。如何才能将正确的类别传递给HttpPost删除操作?
这是我在控制器中得到的东西:
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();
}
}
这是删除视图,正如我所说,正确显示GET上的数据:
<%@ 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>
<% } %>
答案 0 :(得分:0)
您的表单实际上并非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>
<% } %>