0
我正在使用MVC3与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编辑回来时,article.Section为空。如何强制视图将该部分绑定到正在编辑的文章。
任何帮助表示赞赏。
这工作 - 谢谢。看起来很多工作,只是为了绑定一个关联对象。想知道是否有更简单的方法。 – Matt
你可以直接在没有Foreach的情况下直接创建一个SelectList: SelectList oTest = new SelectList(YourListOfObjects,“ValuePropertyOfTheObject”,“TextPropertyOfTheObject”);然后在下拉列表中使用SelectList。 –