【发布时间】:2011-06-28 17:16:57
【问题描述】:
所以我知道 EF 实体会在调用 savechanges 时跟踪它们自己的更改并将它们持久保存到数据库中,但是这种情况呢...
我有一个专为编辑博客文章而设计的页面。它有两种操作方法。
[HttpGet]
public ViewResult EditBlogPost(int Id)
{
//This action method gets the blog post by the id and returns the edit blog post page.
BlogPost blogPost = db.BlogPosts.Where(x => x.Id == Id).FirstOrDefault();
if (blogPost == null)
{
ViewData["message"] = "Blog post not found.";
return View("Result");
}
return View("ManageBlogPost", blogPost);
}
[HttpPost]
public ViewResult EditBlogPost(BlogPost blogPost)
{
//This one is where I'm having issues. When model binding populates blogPost, is it auto-tracking still? For some reason SaveChanges() doesn't seem to persist the updates.
if (!ModelState.IsValid)
return View("ManageBlogPost");
db.AttachTo("BlogPosts", blogPost); //I tried this method, it seemed to be what I wanted, but it didn't help.
db.SaveChanges();
ViewData["message"] = "Blog post edited successfully.";
return View("Result");
}
这是这些返回的视图:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Master.Master" Inherits="System.Web.Mvc.ViewPage<BlogProject.Models.BlogPost>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<% if (Model != null)
{ %>
<h2>Edit Blog Post</h2>
<% }
else
{ %>
<h2>Add Blog Post</h2>
<% } %>
<% using (Html.BeginForm())
{ %>
<% if (Model != null)
{ %>
<%: Html.HiddenFor(x => x.Id)%> <!-- Is this the way to keep un-editable data hidden from the edit form and have them repopulate on the next model bind? What if someone went to modify their POST using something like Fiddler? Couldn't they theoretically edit these fields before the POST? -->
<%: Html.HiddenFor(x => x.Date) %>
<%: Html.HiddenFor(x => x.Author) %>
<%: Html.HiddenFor(x => x.FriendlyUrl) %>
<% } %>
Title:<br />
<%: Html.TextBoxFor(x => x.Title, new { Style = "Width: 90%;" })%>
<br />
<br />
Summary:<br />
<%: Html.TextAreaFor(x => x.Summary, new { Style = "Width: 90%; Height: 50px;" }) %>
<br />
<br />
Body:<br />
<%: Html.TextAreaFor(x => x.Body, new { Style = "Height: 250px; Width: 90%;" })%>
<br />
<br />
<input type="submit" value="Submit" />
<% } %>
</asp:Content>
我在这里有点困惑。添加博客文章似乎可以正常工作,但编辑它们是另一回事。
【问题讨论】:
标签: c# asp.net-mvc entity-framework asp.net-mvc-2 entity-framework-4