我正在寻找一双额外的眼睛,我已经关注了MVC验证的这篇文章http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx。
虽然它是一篇较旧的文章,但大多数概念似乎都是有效的。一切都在C#中工作但是我的项目在VB.NET中,所以我在VB.NET中应用了一个非常简单的版本,但是当检查ModelState.IsValid时,即使title字段为空,它也总是返回True。任何人都可以看到我错在哪里?非常感谢提前。
控制器:
Namespace ValidationTest
Public Class FriendsController
Inherits System.Web.Mvc.Controller
'
' GET: /Friends
Function Index() As ActionResult
Return View()
End Function
Function Create() As ActionResult
Dim friendToCreate As New Person()
Return View(friendToCreate)
End Function
<HttpPost> _
Function Create(friendToCreate As Person) As ActionResult
If (ModelState.IsValid) Then
End If
Return View(friendToCreate)
End Function
End Class
End Namespace
创建视图:
'
' GET: /Friends
Function Index() As ActionResult
Return View()
End Function
Function Create() As ActionResult
Dim friendToCreate As New Person()
Return View(friendToCreate)
End Function
<HttpPost> _
Function Create(friendToCreate As Person) As ActionResult
If (ModelState.IsValid) Then
End If
Return View(friendToCreate)
End Function
End Class
类别:
@ModelType ValidationTest.Person
@Code
ViewData("Title") = "Create"
End Code
@Using Html.BeginForm()
@Html.ValidationSummary(True)
@
Person
@Html.LabelFor(Function(model) model.Title)
@Html.EditorFor(Function(model) model.Title)
@Html.ValidationMessageFor(Function(model) model.Title)
End Using
@Html.ActionLink("Back to List", "Index")
@Section Scripts
@Scripts.Render("~/bundles/jqueryval")
End Section
答案 0 :(得分:2)
您的模型缺少RequiredAttribute
。您也不需要使用底层私有变量定义属性,它由编译器自动生成。
<Required(AllowEmptyStrings:=False, ErrorMessage:="Enter the title")>
Public Property Title As String