考虑以下@razor页面:
For i as Integer = 0 to 4
@Html.TextBoxFor(Function(model) model.Skills(i).Name)
@Html.TextBoxFor(Function(model) model.Skills(i).Title)
@Html.ValidationMessageFor(Function(model) model.Skills(i).Name)
Next
@Html.ValidationMessageFor(Function(model) model.Skills) // <- This one doesnt display validation error message !!
以下型号:
' Model
<MinLength(10)> // this validation runs but (above) doesn't show error messsage
Public Property Skills As SkillsObj()
如何让@Html.ValidationMessageFor(Function(model) model.Skills)
显示错误消息?即使我在Skills数组上执行验证(并且验证正在执行),它也没有。我确实看到了运行其他验证的@Html.ValidationMessageFor(Function(model) model.Skills(i).Name)
的错误消息。
答案 0 :(得分:0)
虽然我不确定以下示例代码是否回答了您的确切问题,但它完全适用于使用DataAnnotations属性的数组项长度验证:
<强>模型强>
Imports System.ComponentModel.DataAnnotations
Public Class MyCustomObjectWithArray
<MinLength(4, ErrorMessage:="Minimum four Employees should be submitted.")>
Public Property EmployeeArray() As Employee()
End Class
Public Class Employee
Public Property Name() As String
Public Property City() As String
End Class
<强>控制器强>
Public Class HomeController
Inherits System.Web.Mvc.Controller
Function Index() As ActionResult
Dim customObject As MyCustomObjectWithArray = New MyCustomObjectWithArray()
customObject.EmployeeArray = New Employee() {}
'Fill the employee array to have only 3 elements so that
' validation fail on form post since Employee array has validation for at least 4 employee names.
For empIndex = 0 To 2
ReDim Preserve customObject.EmployeeArray(empIndex)
customObject.EmployeeArray(empIndex) = New Employee()
Next
Return View("CreateEmployees", customObject)
End Function
<HttpPost>
Function CreateEmployees(ByVal objWithArray As MyCustomObjectWithArray) As ActionResult
If (Not ModelState.IsValid) Then 'Make sure modelstate validation errors are not bypassed.
Return View("CreateEmployees", objWithArray)
End If
'Do stuff like saving to DB or whatever you want with the valid Posted data.
Return RedirectToAction("Index", "Home")
End Function
End Class
查看强>
@ModelType MvcVBApplication.MyCustomObjectWithArray
@Code
ViewData("Title") = "CreateEmployees"
End Code
<h3>CreateEmployees<h3>
@Using (Html.BeginForm("CreateEmployees", "Home"))
Html.EnableClientValidation(True)
@<table>
@If (Model.EmployeeArray IsNot Nothing) Then
For empIndex = 0 To Model.EmployeeArray.Count() - 1
@<tr>
<td>
@Html.TextBoxFor(Function(modelItem) Model.EmployeeArray(empIndex).Name)
</td>
</tr>
Next
Else
@Html.TextBox("(0).Name", "")
End If
</table>
@Html.ValidationMessageFor(Function(m) m.EmployeeArray)
@<br />
@<input type="submit" name="name" value="Submit" />
End Using
希望这会有所帮助。我对VB.NET并不多,所以你可以选择合适的代码结构,如果你发现我使用的那个似乎是旧的方式。