在我的应用程序中,我有一个下拉列表来表示不同的选择。请注意,这Paragraph
是一个模型,该部分只是模型中的一个字段。
@Html.DropDownList("Sections")
这是我的控制器。
public ActionResult Edit(int id)
{
var paragraph = db.Paragraphs.Find(id);
ViewBag.Sections = new SelectList(
db.Sections.Select(s => new { s.ID, s.Name }),
"ID", "Name", paragraph.SectionID
);
return View(paragraph);
}
[HttpPost]
public ActionResult Edit(Paragraph paragraph, HttpPostedFileBase document)
{
if (ModelState.IsValid)
{
// Do some stuff.
}
ViewBag.Sections = new SelectList(
db.Sections.Select(s => new { s.ID, s.Name }),
"ID", "Name", paragraph.SectionID
);
return View(paragraph);
}
当我提交表单时,下拉列表未绑定到模型。造成ModelState.IsValid
虚假,使我的生活变得可怕。有什么建议么?
编辑:当我提交表单时,我收到以下错误:
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Sections'.
编辑:当我尝试提交文件时,我似乎只收到前面的错误。
编辑:模型
public class Paragraph
{
public int ID { get; set; }
[Required]
public int Major { get; set; }
[Required]
public int Minor { get; set; }
[Required(ErrorMessage = "Name is required")]
[StringLength(4000)]
public string Name { get; set; }
public int SectionID { get; set; }
public virtual Section Section { get; set; }
}
形式:(很多。)
<form class="form-horizontal" action="/Paragraph/Edit" method="post" enctype="multipart/form-data">
<fieldset>
<div class="control-group">
<label class="control-label" for="section">Section</label>
<div class="controls">
@Html.DropDownList("Sections")
</div>
</div>
<div class="control-group">
<label class="control-label" for="major">Major</label>
<div class="controls">
<input type="number" class="input-large" name="major" value="@Model.Major" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="minor">Minor</label>
<div class="controls">
<input type="number" class="input-large" name="minor" value="@Model.Minor" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<input type="text" class="input-large" name="name" value="@Model.Name" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="document">Document</label>
<div class="controls">
<input type="file" class="input-file" name="document" />
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="Save" />
<a class="btn" href="/Paragraph/Show/@Model.ID">Cancel</a>
</div>
</fieldset>
</form>