私は柔軟なフォームを持っています。ドロップダウンリストで行う選択に応じて、フィールドが異なることを意味します。また、呼び出されるコントローラーのアクションも変わります。簡単な例でこれを機能させようとしていますが、データをコントローラーに送信し、コントローラーがそれを定義済みのクラスに正しくマップする方法を見つけることができません。
明確化: ユーザーが選択肢が 1 つしかない新しい質問を作成する場合、これはユーザーが使用しているフォーム/コントローラーです。ただし、複数の選択肢がある質問を作成するときは、同じフォーム/コントローラーを使用したいと思います。私が得ているエラーは、オブジェクトがnullであることです。これは、データがコントローラーに渡されるたびに、オブジェクトに適切にマップされていないことを意味すると思います。定義済みのオブジェクトにデータを明示的にマップするにはどうすればよいですか? それとも、この全体を別の方法で行う必要がありますか?
コントローラーは次のとおりです。
[HttpPost]
public ActionResult CreateSimpleQuestion(SimpleQuestion question)
{
if (ModelState.IsValid)
{
question.question.is_counted = true;
question.question.DateCreated = DateTime.Now;
db.Questions.Add(question.question);
db.QuestionChoices.Add(question.choices[0]);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(question);
}
クラスは次のとおりです。
[Serializable]
public class SimpleQuestion
{
public Question question { get; set; }
public QuestionChoices[] choices { get; set; }
}
コントローラー アクションを呼び出すスクリプトは次のとおりです。
<script type="text/javascript">
$("form").on("submit", function (event) {
event.preventDefault();
var data = $('form').serialize();
console.log(data);
$.post('/Question/CreateSimpleQuestion/', data);
});
</script>
これはシリアル化されたデータです。
QuestionTitle=faketitle&Keywords=fakekeywords&Description=fakedescription&Comments=fakecomments&QuestionType=Simple&DisplayText=fakequestiontext&OrderNumber=fakeorder
そして、モデルの詳細が必要な場合:
public class Question
{
public int QuestionId { get; set; }
public string QuestionTitle { get; set; }
public DateTime DateCreated { get; set; }
public string QuestionType { get; set; }
public string Keywords { get; set; }
public bool is_counted { get; set; }
public int? ParentId { get; set; }
[Column(TypeName = "ntext")]
[MaxLength]
public string Description { get; set; }
[Column(TypeName = "ntext")]
[MaxLength]
public string Comments { get; set; }
//These define a one to many relationship
public virtual ICollection<TeamQuestionRoster> TeamQuestionRosters { get; set; }
public virtual ICollection<Response> Responses { get; set; }
public virtual ICollection<QuestionChoices> QuestionChoices { get; set; }
}
public class QuestionChoices
{
public int QuestionChoicesId { get; set; }
public string DisplayText { get; set; }
public int OrderNumber { get; set; }
public bool is_correct { get; set; }
//These are the FK properties
public int QuestionId { get; set; }
//This defines the FK Relationships
public virtual Question Question { get; set; }
//These define a one to many relationship
public virtual ICollection<ResponseDetails> ResponsDetails { get; set; }
}