由于我是asp.net mvc 3的新手,我对其内部过程并不了解。我有两个作用,以创建新的类别为获取和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处于调试模式时才引发异常,而wh我继续调试,然后只验证消息中显示错误。在这里,实际上必须是错误应该显示,而不是在调试模式下抛出异常,这是正常的。我已经在数据库以下类别表列,并使用模型第一种方法实体框架:
- ID - >主键和身份,整数
- 类别名称 - >非空,VARCHAR(50)
- ParentCategoryID - >可空
我不擅长asp.net mvc 3,不知道可能是什么问题。
我已经完成了你所说的但显示了'编译器错误消息:CS1660:不能将lambda表达式转换为键入'string',因为它不是委托类型'。这里,ParentCategoryID是整数类型。有没有其他的方法 – CodeManiac 2012-07-12 06:18:35
在哪条线上抛出这个错误? – 2012-07-12 06:23:35
感谢您的回答。最后我有解决方案。问题在于CategoryName字符串由于预绑定验证而转换为空,因此我添加了DisplayFormat属性(ConvertEmptyStringToNull = false)。现在,我不会抛出异常,并显示客户端验证消息 – CodeManiac 2012-07-12 06:41:03