我仍然在努力学习ASP.NET MVC。我所有的表单条目都是必需的,所以我想对它们进行验证。为简洁起见,我将我的模型与Description(文本框)和Paradigm(下拉列表)配对。我包括Entry.cs,Paradigm.cs和EntryViewModel.cs模型类以及Display.cshtml视图。
[Bind(Exclude = "EntryId")]
public class Entry
{
[ScaffoldColumn(false)]
public int EntryId { get; set; }
[Required(ErrorMessage = "You must include a description.")]
public string Description { get; set; }
[Display(Name = "Type")]
[Required(ErrorMessage = "You must select a type.")]
public int ParadigmId { get; set; }
public virtual Paradigm Paradigm { get; set; }
}
public class Paradigm
{
[ScaffoldColumn(false)]
public int ParadigmId { get; set; }
[Required]
public string Name { get; set; }
public List<Entry> Entries { get; set; }
}
public class EntryViewModel
{
public Entry Entry { get; set; }
public IEnumerable<Entry> Entries { get; set; }
}
@model Pylon.Models.EntryViewModel
@{
ViewBag.Title = "Display";
}
<hr />
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Entry</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Entry.Description)
</div>
<div class="editor-field">
@Html.TextAreaFor(model => model.Entry.Description)
@Html.ValidationMessageFor(model => model.Entry.Description)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Entry.ParadigmId)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Entry.ParadigmId, ((IEnumerable<Pylon.Models.Paradigm>)ViewBag.PossibleParadigms).Select(option => new SelectListItem {
Text = (option == null ? "None" : option.Name),
Value = option.ParadigmId.ToString(),
Selected = (Model != null) && (option.ParadigmId == Model.Entry.ParadigmId)
}))
<a href="@Url.Action("Paradigm")"><img src="../../Content/Images/add_icon.gif" /></a>
@Html.ValidationMessageFor(model => model.Entry.ParadigmId)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
如果我在未输入说明的情况下提交表单,我希望验证可以启用并说“您必须包含说明”。但是我在DropDownFor行上收到了ArgumentNullException。 http://www.wvha.org/temp/ArgumentNullException.png
我该怎么办?除了任何涵盖ASP.NET MVC 3 / Razor的体面书籍。我可以按照基本的方式进行,但是当我需要偏离更高级的功能时,我会误入歧途。
public class EntriesController : Controller
{
private readonly PylonContext _context = new PylonContext();
public ActionResult Display()
{
// DropDown
ViewBag.PossibleParadigms = _context.Paradigms;
var viewModel = new EntryViewModel {Entries = _context.Entries.ToList()};
return View(viewModel);
}
[HttpPost]
public ActionResult Display(EntryViewModel viewModel)
{
if (ModelState.IsValid)
{
_context.Entries.Add(viewModel.Entry);
_context.SaveChanges();
return RedirectToAction("Display");
}
return View(viewModel);
}
}
答案 0 :(得分:3)
如果没有看到您的控制器代码,很难说,但看起来您的ViewBag.PossibleParadigms
可能为空。
您的插入/更新控制器操作是否看起来像这样?
if (ModelState.IsValid) {
///...
} else {
return View(model);
}
如果是这样,您需要在返回视图之前将PossibleParadigms放回ViewBag(可以这么说)。
如果您可以发布相关的控制器操作代码,那么肯定会更容易知道。