フォームの送信を使用してViewModelをコントローラに渡そうとしています。 ViewModelがPOSTメソッドに到達すると、無効でnullになります。ポストでモデルが無効です
VraagViewModel:
public class VraagViewModel
{
public List<Thema> Themas { get; set; }
public List<Gevolg> Condities { get; set; }
public Vraag Vraag { get; set; }
public List<Gevolg> GekozenCondities { get; set; }
public Thema Thema { get; set; }
public Antwoord Antwoord { get; set; }
}
コントローラー:
[HttpGet]
public ActionResult Index()
{
UnitOfWorkManager uow = new UnitOfWorkManager();
IThemaManager mgr = new ThemaManager(uow);
ITestManager testmgr = new TestManager(uow);
Models.VraagViewModel model = new Models.VraagViewModel
{
Themas = mgr.GetThemas().ToList(),
Condities = testmgr.GetGevolgen().ToList(),
GekozenCondities = new List<Gevolg>()
};
return View(model);
}
[HttpPost]
public void Index(Models.VraagViewModel model)
{
Debug.WriteLine(model.GekozenCondities.Count); //Nullpointer here!
if (!ModelState.IsValid)
Debug.WriteLine("ModelState not valid!");
}
Index.cshtml:
@model UI.Mvc.Areas.Admin.Models.VraagViewModel
@{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<h2>Vraagbeheer</h2>
@using (Html.BeginForm())
{
<p>@Html.DropDownList("Themas", new SelectList(Model.Themas))</p>
<p>@Html.TextArea("vraag", "Hier komt de vraagtekst")</p>
<p>@Html.ListBox("Condities1", new SelectList(Model.Condities), new { id =
"condities1" })</p>
<p>@Html.ListBox("Condities2", new SelectList(Model.GekozenCondities), new {
id = "condities2" })</p>
<p><button type="button" id="add" class="btn btn-default">Conditie
toevoegen</button></p>
<p><button type="button" id="remove" class="btn btn-default"
onclick="verwijderConditie">Conditie verwijderen</button></p>
@Html.TextArea("antwoord1", "Voor- en nadelen\nAntwoord1")
@Html.TextArea("antwoord2", "Voor - en nadelen\nAntwoord2")
@Html.TextArea("antw1Kort", "Antwoord 1")
@Html.TextArea("antw2Kort", "Antwoord 2")
<input id="gevolgInvullen" type="submit" value="Gevolgen invullen"
class="btn btn-default" />
}
@section scripts{
<script type="text/javascript">
$(function() {
$("#add").bind("click", function (e) {
$("#condities1 > option:selected").each(function() {
$(this).remove().appendTo("#condities2");
});
e.preventDefault();
});
$("#remove").bind("click", function (e) {
$("#condities2 > option:selected").each(function() {
$(this).remove().appendTo("#condities1");
});
e.preventDefault();
});
/*$("gevolgInvullen").bind("click", function() {
Url.Action("Action", "Controller")
})*/
});
</script>
}
質問
コントローラのPOSTメソッドに到着したときにViewModelがnullになる原因を知りたいと思います。
EDIT 1
モデル自体is not null.
GekozenConditiesプロパティではないモデルであることを確認しましたか? – Andrei
あなたは正確なエラーメッセージを投稿することができます – Ogbe
それはモデル自体がnullではないようです。 GekozenConditiesとThemas(どちらもCount = 0)を除き、モデル内のすべてがnullです。 – Xander