ZVe*_*nue 2 asp.net-mvc entity-framework entity-framework-4 asp.net-mvc-3
按照这个例子.. 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();
}
}
Run Code Online (Sandbox Code Playgroud)
在我检查的参数'blog'中没有得到需要删除的实际博客模型.所有其他方法工作正常(编辑,删除(获取)..等..但删除帖子失败.我错过了什么?提前感谢帮助.
编辑:
查看代码
@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>
}
Run Code Online (Sandbox Code Playgroud)
编辑2:非剃刀代码:
<% using (Html.BeginForm()) { %>
<p>
<input type="submit" value="Delete" /> |
<%: Html.ActionLink("Back to List", "Index") %>
</p>
<% } %>
Run Code Online (Sandbox Code Playgroud)
编辑3 :(我试过aspx)
<% using (Html.BeginForm()) { %>
<p>
<%=Html.DisplayForModel();%> //Tried Html.EditorForModel also..
<input type="submit" value="Delete" /> |
<%: Html.ActionLink("Back to List", "Index") %>
</p>
<% } %>
Run Code Online (Sandbox Code Playgroud)
最终编辑(更正的解决方案)
@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>
}
Run Code Online (Sandbox Code Playgroud)
上下文可能没有您的博客条目,因为它没有附加到上下文.
您可能需要首先检索博客,然后使用以下Entry方法将其标记为已删除:
[HttpPost]
public ActionResult Delete(int id, Blog blog)
{
try
{
using (var db = new BlogDataEntities())
{
// retrieve the blog from the database
var realBlog = db.Blogs.Find(blog.Id);
// nothing to do here, just redirect
if( realBlog == null )
return RedirectToAction("Index");
// since you have the entity just do this instead:
db.Blogs.Remove(realBlog);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch( Exception )
{
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
我不同意将您的实体用作模型的想法.您应该使用View Models.
编辑
既然您现在说博客没有通过,请试试这个:
@model Blog
@using ( Html.BeginForm() )
{
@Html.EditorForModel()
<input type="submit" value="Delete" />
}
Run Code Online (Sandbox Code Playgroud)
您实际上并没有给模型绑定器提供构建模型所需的任何细节.
| 归档时间: |
|
| 查看次数: |
3853 次 |
| 最近记录: |