【发布时间】: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