我正在尝试使用 MVC 2 从数据库中删除一条记录。当前删除功能工作正常,但有一些具有外键关系的记录,所以我不会删除它们,当用户尝试删除我想要的此类记录时在删除视图上显示错误消息而不导航到另一个视图。
控制器:
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
StockRepository rep = new StockRepository();
Stock stock = rep.GetStock(id);
rep.Delete(stock);
rep.Save();
return RedirectToAction("Index");
}
catch
{
//need to display an error message if unable to delete
return View();
}
}
看法:
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>Fields</legend>
<div class="display-label">StockID</div>
<div class="display-field"><%: Model.StockID %></div>
<div class="display-label">ClientName</div>
<div class="display-field"><%: Model.ClientName %></div>
<div class="display-label">ItemName</div>
<div class="display-field"><%: Model.ItemName %></div>
<div class="display-label">ItemCount</div>
<div class="display-field"><%: Model.ItemCount %></div>
<div class="display-label">Price</div>
<div class="display-field"><%: String.Format("{0:F}", Model.Price) %></div>
<div class="display-label">OtherExpences</div>
<div class="display-field"><%: String.Format("{0:F}", Model.OtherExpences) %></div>
<div class="display-label">TotalStockValue</div>
<div class="display-field"><%: String.Format("{0:F}", Model.TotalStockValue) %></div>
<div class="display-label">DeliveryDate</div>
<div class="display-field"><%: String.Format("{0:d}", Model.DeliveryDate) %></div>
<div class="display-label">Description</div>
<div class="display-field"><%: Model.Description %></div>
</fieldset>
<% using (Html.BeginForm()) { %>
<p>
<input type="submit" value="Delete" /> |
<%: Html.ActionLink("Back to List", "Index") %>
</p>
<% } %>