Che*_*hev 8 c# asp.net-mvc entity-framework entity-framework-4 asp.net-mvc-2
所以我知道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");
}
Run Code Online (Sandbox Code Playgroud)
以下是这些回归的观点:
<%@ 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>
Run Code Online (Sandbox Code Playgroud)
我在这里有点困惑.添加博客文章似乎工作正常,但编辑它们是另一个故事.
解决方案不是在编辑操作方法中接受博客文章对象.相反,做一些看起来像这样的事情:
[HttpPost]
public ViewResult EditBlogPost(int postID)
{
var post = db.BlogPosts.Single(p => p.PostID = postID);
TryUpdateModel(post);
if (!ModelState.IsValid)
return View("ManageBlogPost");
db.SaveChanges();
ViewData["message"] = "Blog post edited successfully.";
return View("Result");
}
Run Code Online (Sandbox Code Playgroud)
这样,对象附加到上下文,EF可以正确跟踪更改.该UpdateModel
方法可以节省时间,自动将表单集合中的字段与模型中的字段进行匹配,并为您更新它们.
下面是文档UpdateModel
:
MSDN
归档时间: |
|
查看次数: |
9536 次 |
最近记录: |