コントローラーがポストバックのサブクラス モデルを認識するのに問題があります。
データベースに格納されたフィールド メタ データを使用して、動的な Web フォームを作成しています。私のViewModelには、2つの親タイプがあります
public class Form
{
public List<Question> Questions { get; set; }
}
public class Question
{
public string QuestionText { get; set; }
}
および Question のサブクラス
public class TextBoxQuestion : Question
{
public string TextAnswer { get; set; }
public int TextBoxWidth { get; set; }
}
また、フォーム タイプをモデルとして使用するビューと、2 つの表示テンプレート (1 つは質問用、もう 1 つはフォーム TextBoxQuestion 用) を使用するビューもあります。
//Views/Form/index.cshtml
@model Form
@Html.DisplayFor(m => m.Questions)
-
//Views/Shared/DisplayTemplates/Question.cshtml
@model Question
@if(Model is TextBoxQuestion)
{
@Html.DisplayForModel("TextBoxQuestion")
}
-
//Views/Shared/DisplayTemplates/TextBoxQuestion.cshtml
@model TextBoxQuestion
<div>
@Model.QuestionText
@Html.TextBoxFor(m => m.TextAnswer)
</div>
ページが読み込まれると、コントローラーは TextBoxQuestion のインスタンスを作成し、それを Question コレクションに追加して、Form オブジェクトをビューに渡します。すべてが機能し、テキストボックスがページに表示されます。
しかし、コントローラーにポストバックすると、コードは質問を TextBoxQuestion として認識しません。親タイプの質問としてのみ認識されます。
[HttpPost]
public ActionResult Index(Form f)
{
foreach (var q in f.Questions)
{
if (q is TextBoxQuestion)
{
//code never gets here
}
else if (q is Form)
{
//gets here instead
}
}
}
足りないものはありますか?