gpt4 book ai didi

.net - MVC3 客户端对集合的验证,至少有一个元素具有值

转载 作者:行者123 更新时间:2023-12-01 06:39:17 25 4
gpt4 key购买 nike

我的 View 模型

Public Class ViewModel
<SelectOne()>
Public Property Collection As List(Of Item)
End Class

我的模特
Public Class Item
<SelectOneProperty(TargetValue:=True, ErrorMessage:="Select at least one.")>
Public Property Selected As Boolean
Public Property Value As String
End Class

在我看来,我正在渲染 ViewModel.Collection使用编辑器模板
@Html.CheckBoxFor(Function(item) item.Selected)
@Html.HiddenFor(Function(item) item.Value)

现在,我想要的是确保使用客户端验证至少选中一个复选框。

我可以通过在 Item.Selected 上设置自定义验证属性来实现这一点。属性并通过 $.validator.unobtrusive.adapters.add() 注册新适配器

但我觉得属性应该放在 ViewModel.Collection上在服务器端的属性我已经在验证集合的项目之一是否具有 Selected = True使用此自定义验证:
<AttributeUsage(AttributeTargets.Field Or AttributeTargets.Property, AllowMultiple:=False, Inherited:=False)>
Public Class SelectOneAttribute
Inherits ValidationAttribute

Protected Overrides Function IsValid(value As Object, validationContext As ValidationContext) As ValidationResult

Dim list As IList

If value Is Nothing Then
Return Nothing
End If

If TypeOf value Is IEnumerable Then
list = CType(value, IList)
Else
list = New Object() {value}
End If

Dim count As Integer = (From item In list
From prop In item.GetType().GetProperties()
Let attributes = prop.GetCustomAttributes(GetType(RequireOneOrMoreIndicatorAttribute), False)
Where attributes.Count > 0
From attribute In attributes
Where attribute.TargetValue = prop.GetValue(item, Nothing)).Count()
If count > 0 Then
Return Nothing
End If

Return New ValidationResult(FormatErrorMessage(validationContext.DisplayName))
End Function
End Class

它在 SelectOnePropertyAttribute 上使用反射查找要检查的属性:
<AttributeUsage(AttributeTargets.Field Or AttributeTargets.Property, AllowMultiple:=False, Inherited:=False)>
Public Class SelectOnePropertyAttribute
Inherits ValidationAttribute
Implements IClientValidatable

Public Property TargetValue As Object

Public Sub New(targetValue As Object)
Me.TargetValue = targetValue
End Sub

Public Overrides Function IsValid(value As Object) As Boolean
Return True
End Function

Public Function GetClientValidationRules(metadata As System.Web.Mvc.ModelMetadata, context As System.Web.Mvc.ControllerContext) _
As System.Collections.Generic.IEnumerable(Of System.Web.Mvc.ModelClientValidationRule) _
Implements System.Web.Mvc.IClientValidatable.GetClientValidationRules

Dim rule As New ModelClientValidationRule With {
.ValidationType = "selectone",
.ErrorMessage = Me.ErrorMessage
}

Return New ModelClientValidationRule() {rule}
End Function
End Class

这是客户端验证
$.validator.unobtrusive.adapters.add("selectone", function (options) {
options.rules["selectone"] = {};
options.messages["selectone"] = options.message;
});

$.validator.addMethod("selectone", function (value, element, parameters) {

var $el = $(element),
name = $el.attr("name"),
field = name.replace(/\[.*$/, "").replace(".", "_"),
attr = name.replace(/^.*\./, ""),
test = new RegExp(field + "\\[\\d\\]\." + attr);

var inputs = $("input[id^=" + field + "]:not([disabled]):not([type=hidden])").filter("input[name$=" + attr + "]");

for(var i = 0; i < this.errorList.length; i++) {
var name = $(this.errorList[i].element).attr("name");

// Do not write out the error more than once.
if (test.test(name)) return true;
}

return inputs.length == 0 || inputs.filter(":checked:not([disabled])").val();
});

最佳答案

您正在创建将在侧面运行的自定义验证,但如果您想在客户端运行,那么您必须为该自定义验证创建 JQuery,然后将其添加到您的页面。

请引用以下链接

http://www.codeproject.com/Articles/275056/Custom-Client-Side-Validation-in-ASP-NET-MVC3

http://www.falconwebtech.com/post/2012/04/21/MVC3-Custom-Client-Side-Validation-with-Unobtrusive-Ajax.aspx

关于.net - MVC3 客户端对集合的验证,至少有一个元素具有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12388300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com