【发布时间】:2011-09-08 10:21:55
【问题描述】:
所以我使用 EF Code First 成功创建了我的实体并查询数据库以显示项目。
我现在想提供一种编辑记录的方法。
我有一个 Post 类,其中包含:
(TypeName = "varchar")]
[Required()]
public string Headline { get; set; }
public virtual PostType PostType { get; set; }
PostType 是我编写的一个类,它有一个 ID 和名称,用于将帖子分类为新闻、博客等。
现在,在我的编辑控制器中,我得到了帖子并将其传递给视图模型中的视图。我还得到了不同帖子类型的 IEnumerable。
在我看来,我使用以下内容:
<div class="formFieldContainer">
@Html.LabelFor(model => model.Post.PostType)
@Html.DropDownListFor(model => model.Post.PostType, new SelectList(Model.PostTypes, "ID", "Name"))
@Html.ValidationMessageFor(model => model.Post.PostType)
</div>
<div class="formFieldContainer">
@Html.LabelFor(model => model.Post.Headline)
@Html.EditorFor(model => model.Post.Headline)
@Html.ValidationMessageFor(model => model.Post.Headline)
</div>
在我的编辑控制器上,我有以下内容来处理帖子:
[HttpPost, ValidateAntiForgeryToken, ValidateInput(false)]
public ActionResult Edit(int id, FormCollection collection) {
var model = new PostViewModel();
model.Post = _pr.GetPost(id); //gets the post from my post repository
model.PostTypes = _ptr.GetPostTypes();
try {
UpdateModel(model.Post, "Post");
_pr.Save();
return RedirectToRoute("Posts", new { pageNumber = 0 }); //for now go to the homepage
} catch (Exception e) {
ModelState.AddModelError("_FORM", e.Message);
return View(model);
}
}
现在没有帖子类型列表,只有标题可以正常工作。但是,对于帖子类型,它不会。我得到“1 无效”(1 是选择列表的值),这是有道理的,因为我的 Post 模型需要一个 PostType 对象,而不是 int。
我想过做类似的事情:
model.Post.PostType = model.PostTypes.Where(x => x.ID == Int32.Parse(collection.GetValues("Post.PostType")[0])).Select(p => p).FirstOrDefault();
但是 1)它不起作用,所以它显然不是正确的方法,2)由于“Post.PostType”仍然存在,UpdateModel 失败。
关于如何做到这一点的任何想法?
【问题讨论】:
-
不起作用是什么意思?没有细节就帮不上忙。
-
另一个 PostType 被添加到数据库中!它应该是现有的,但每次都在创建一个新的。
标签: c# asp.net asp.net-mvc-3 entity-framework-4 ef-code-first