我仍在努力學習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