質問の作成ビューでDropDownListを手動で作成している質問クラスにナビゲーションプロパティ(カテゴリ)があり、作成アクションを投稿すると、カテゴリナビゲーションプロパティがモデルに入力されないため、無効な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; }
}
Createの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フィールドはビューで選択したCategoryに設定されます。
ビューから取得したCategoryId値を使用して、EFでカテゴリを手動でフェッチするコードを簡単に追加できることを知っています。これを行うためのカスタムバインダーを作成することもできると思いますが、これがデータアノテーションを使用して実行できることを望んでいました。
私は何かが足りないのですか?
ナビゲーションプロパティのドロップダウンリストを生成するためのより良い方法はありますか?
手動で行うことなく、MVCにナビゲーションプロパティを設定する方法を知らせる方法はありますか?
- 編集:
違いが生じる場合は、質問を作成/保存するときに実際のナビゲーションプロパティをロードする必要はありません。必要なのは、CategoryIdをデータベースに正しく保存することだけです。これは発生しません。
ありがとう