【发布时间】:2011-08-19 08:23:19
【问题描述】:
我正在使用带有 EF 4.1 的 MVC3 并尝试编辑具有下拉列表的模型,该下拉列表是对父对象的引用。以下是模型:
public class Section
{
public Guid SectionId { get; set; }
public string Title { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
public class Article
{
public Guid ArticleId { get; set; }
public DateTime? DatePosted { get; set; }
public string Title { get; set; }
public string ArticleBody { get; set; }
public Section Section { get; set; }
}
这是呈现编辑的 GET 部分的控制器操作:
public ActionResult Edit(Guid id)
{
Article article = db.Articles.Find(id);
var sections = db.Sections.ToList();
var secIndex = sections.IndexOf(article.Section);
ViewBag.SectionId = new SelectList(sections, "SectionId", "Title", secIndex);
return View(article);
}
还有风景
@model CollstreamWebsite.Models.Article
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Article</legend>
@Html.HiddenFor(model => model.ArticleId)
<div class="editor-label">
@Html.LabelFor(model => model.DatePosted)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DatePosted)
@Html.ValidationMessageFor(model => model.DatePosted)
</div>
...
<div class="editor-label">
@Html.LabelFor(model => model.Section)
</div>
<div class="editor-field">
@Html.DropDownList("SectionId")
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
最后是编辑的 POST 操作
[HttpPost]
public ActionResult Edit(Article article)
{
if (ModelState.IsValid)
{
db.Entry(article).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(article);
}
我遇到的问题是,当 HttpPost Edit 返回时,article.Section 为空。如何强制视图将 Section 绑定到正在编辑的文章。
任何帮助表示赞赏。
【问题讨论】:
标签: entity-framework asp.net-mvc-3 binding drop-down-menu