私はASP.NET MVCを初めて使用しています。私は初めてのプロジェクトで楽しみにしています。 私はこのArgumentNullExceptionを取得し、何が間違っているのか理解できません。C#razorview DropDownListFor '値はnullにはなりません'
これは私のモデルである:
public class SpeciesLabel
{
[Key]
[Required]
public string Name { get; set; }
[Required]
public CustomGroup CustomGroup { get; set; }
[Required]
public Family Family { get; set; }
[Required]
public Genus Genus { get; set; }
[Required]
public Species Species { get; set; }
}
public class SpeciesLabelDbContext : DbContext
{
public SpeciesLabelDbContext()
: base("DefaultConnection")
{
}
public DbSet<SpeciesLabel> SpeciesLabel { get; set; }
}
これはコントローラです:
public ActionResult Create()
{
List<SelectListItem> customGroups = new List<SelectListItem>();
IQueryable<string> customGroupsQuery = from g in customGroupsDb.CustomGroup
select g.Name;
foreach (var element in customGroupsQuery)
{
customGroups.Add(new SelectListItem()
{
Value = element,
Text = element
});
}
ViewBag.CustomGroup = customGroups;
これは、コントローラのPOSTリクエストです:
public ActionResult Create([Bind(Include = "CustomGroup,Family,Genus,Species")] SpeciesLabel speciesLabel)
{
if (ModelState.IsValid)
{
db.SpeciesLabel.Add(speciesLabel);
db.SaveChanges();
return RedirectToAction("Create");
}
return View();
}
そして、これが図である。
<pre>
@model PlantM.Models.PlantModels.SpeciesLabel
@{
ViewBag.Title = "Create";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Species label</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.CustomGroup, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.CustomGroup, new SelectList(ViewBag.CustomGroupList, "Value", "Text"), "Please select...", new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CustomGroup, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
</pre>
私はビュー内のすべてのプロパティの入力を持っていますが、私はそれらを同じものにカットしていますが、例外は同じです。プロパティ名は、コントローラで設計される(他のプロパティの連結)ので、ビューから返されません。
これは私がフォームを送信するときに私が得る例外です:
編集:
POSTでViewBagの初期化を追加した後のメソッドを作成します例外ArgumentNullExceptionでの問題が解決されているが、IまだNull値の引数を受け取り、このためオブジェクトを作成することができず、Createビューが何度も呼び出されます。誰もこれらの@ Html.DropDownListForがコントローラに値を投稿しない理由を助言できますか?
あなたは 'ViewBag.CustomGroupList'がNULLだと言っていますか? – pookie
私はドロップダウンメニューのリストを参照するので、私はそれがnullではないと思うが、私はオプションを選択し、私はこの例外を取得する送信ボタンをクリックします。私はコントローラにデータを送り返すことに問題があると思うが、何が間違っているのか分からない。 –
[HttpPost]を作成アクションの上に置きますか? – pookie