【发布时间】:2013-03-12 17:12:01
【问题描述】:
我在 Question 类上有一个导航属性 (Category),我在 Question 的 Create 视图中手动为其创建 DropDownList ,并且在发布 Create 操作时,Category 导航属性不会填充到模型上,因此给我一个无效的 ModelState。
这是我的模型:
public class Category
{
[Key]
[Required]
public int CategoryId { get; set; }
[Required]
public string CategoryName { get; set; }
public virtual List<Question> Questions { get; set; }
}
public class Question
{
[Required]
public int QuestionId { get; set; }
[Required]
public string QuestionText { get; set; }
[Required]
public string Answer { get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
public int CategoryId { get; set; }
}
这是我的问题控制器,用于创建的 GET 和 POST 操作:
public ActionResult Create(int? id)
{
ViewBag.Categories = Categories.Select(option => new SelectListItem {
Text = option.CategoryName,
Value = option.CategoryId.ToString(),
Selected = (id == option.CategoryId)
});
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Question question)
{
if (ModelState.IsValid)
{
db.Questions.Add(question);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(question);
}
这里是问题的创建视图
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Question</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Category)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Category.CategoryId, (IEnumerable<SelectListItem>)ViewBag.Categories, "Select a Category")
</div>
<div class="editor-label">
@Html.LabelFor(model => model.QuestionText)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.QuestionText)
@Html.ValidationMessageFor(model => model.QuestionText)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Answer)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Answer)
@Html.ValidationMessageFor(model => model.Answer)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
我尝试了以下在视图上生成下拉列表的变体:
@Html.DropDownListFor(model => model.Category.CategoryId, (IEnumerable<SelectListItem>)ViewBag.Categories, "Select a Category")
@Html.DropDownListFor(model => model.Category, (IEnumerable<SelectListItem>)ViewBag.Categories, "Select a Category")
@Html.DropDownList("Category", (IEnumerable<SelectListItem>)ViewBag.Categories, "Select a Category")
@Html.DropDownList("CategoryId", (IEnumerable<SelectListItem>)ViewBag.Categories, "Select a Category")
当我在 POST 操作上快速查看 Question 对象时,Category 属性为 null,但该属性上的 CategoryId 字段设置为视图上的选定类别。
我知道我可以使用从视图中获得的 CategoryId 值轻松添加代码以手动获取具有 EF 的类别。我也认为我可以创建一个自定义活页夹来执行此操作,但我希望这可以通过数据注释来完成。
我错过了什么吗?
有没有更好的方法来为导航属性生成下拉列表?
有没有办法让 MVC 知道如何填充导航属性而无需我手动执行?
-- 编辑:
如果有什么不同,我不需要在创建/保存问题时加载实际的导航属性,我只需要将 CategoryId 正确保存到数据库中,这不会发生。
谢谢
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-4 data-annotations modelbinders navigation-properties