我仍在努力学习ASP.NET MVC。我所有的表单条目都是必需的,所以我想对它们进行验证。为简洁起见,我已将模型配对到Description(文本框)和Paradigm(下拉框)。我包括Entry.cs,Paradigm.cs和EntryViewModel.cs模型类和Display.cshtml视图。ASP.NET MVC DropDownFor验证(值不能为空参数名称:源)
[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);
}
}
向我们显示您对DropDownFor的呼叫。很可能,它无法弄清楚它应该填充下拉列表的内容。 – StriplingWarrior 2011-02-28 22:07:10
只是一个提示:不是在Visual Studio中发布异常屏幕截图,而是发布堆栈跟踪信息,该信息确切地显示异常来自何处。您可以从异常消息中的* View detail ... *链接中获取堆栈跟踪。 – jevakallio 2011-02-28 22:17:56