我是ASP.NET MVC的新手,我正在开发我的第一个项目,只是为了好玩 . 我得到这个ArgumentNullException,我无法弄清楚出了什么问题 .
这是我的模特:
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>
我有视图中所有属性的输入,但我切割它们,因为它们与此类似,并且异常将是相同的 . 仅从视图中返回属性Name,因为它将在控制器中设计(其他属性的串联) .
这是我提交表单时遇到的例外情况:
编辑:
在POST Create方法中添加ViewBag初始化后,ArgumentNullException的问题得到解决,但我仍然收到Null值参数,因此无法创建对象,并且一次又一次地调用Create视图!任何人都可以建议为什么这些@ Html.DropDownListFor不向控制器发布任何值?
1 回答
从评论中,听起来就像您在第一次访问时看到的视图,但是在您发布后会发生null异常 .
如果上面的假设是正确的,那么我认为你的问题是因为当你回发时, your model did not pass the validation (例如,可能是一个必需的输入字段没有回发值),这意味着
ModelState.IsValid
是假的,所以return View()
被调用这是问题, you are not setting 在返回之前
ViewBag.CustomGroup = customGroups;
,因此ViewBag.CustomGroup
为空,这就是你看到异常的原因 .初始化ViewBag就像你如何做到这一点然后你应该能够看到页面 .