由于我是 asp.net mvc 3 的新手,所以我对它的内部流程一无所知。我有两个动作来创建新类别作为 Get 和 Post 方法:
public ActionResult Create()
{
List<Category> cat = this.display_children(null, 0);
List<SelectListItem> items = new SelectList(cat, "ID", "CategoryName").ToList();
items.Insert(0, (new SelectListItem { Text = "root", Value = "" }));
ViewBag.ParentCategoryID = items;
return View();
}
[HttpPost]
public ActionResult Create(Category category)
{
if (ModelState.IsValid)
{
db.Categories.AddObject(category);
db.SaveChanges();
return RedirectToAction("Index");
}
List<Category> cat = this.display_children(null, 0);
List<SelectListItem> items = new SelectList(cat, "ID", "CategoryName").ToList();
items.Insert(0, (new SelectListItem { Text = "root", Value = "" }));
ViewBag.ParentCategoryID = items;
return View(category);
}
下面是视图:
@model IVRControlPanel.Models.Category
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Category</legend>
<div class="editor-label">
@Html.LabelFor(model => model.CategoryName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CategoryName)
@Html.ValidationMessageFor(model => model.CategoryName)
</div>
<div class="editor-label">
@Html.Label("Select Category")
</div>
<div>
@*@Html.DropDownList("CategoryList",new SelectList(ViewBag.Categories))*@
@Html.DropDownList("ParentCategoryID", ViewBag.ParentCategoryID as SelectList)
@Html.ValidationMessageFor(model => model.ParentCategoryID)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
问题:当我单击创建按钮而不填写类别名称字段时,会引发以下异常:
This property cannot be set to a null value.
仅当 Visual Studio 处于调试模式时才会引发异常,并且当我继续调试时,验证消息中只会显示错误。在这里,实际上必须是在不引发异常的情况下显示错误,这在不处于调试模式时是可以的。我在数据库中有以下类别表列并使用模型优先方法实体框架:
- ID -> 主键和身份,整数
- CategoryName -> 不可为空,varchar(50)
- ParentCategoryID -> 可以为空
我不擅长 asp.net mvc 3,也不知道可能是什么问题。