So I know that EF entities track their own changes and persist them to the database when savechanges is called, but what about this scenario...
I have a page that is designed to edit a blog post. It has two action methods.
[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");
}
Here is the view that these return:
<%@ 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>
I'm a little confused here. Adding blog posts seems to work fine, but editing them is another story.