2

jQuery の目立たない検証を使用して MVC3 を把握するのに苦労しています。

リクエストを行う前に、ユーザーが少なくとも1 つのフィールドに入力する必要があるフォームがありますPOST

私はDarin Dimitrov の Answer Hereにかなり従いましたが、フィールドに値がない場合、フォームの送信を停止するために何をする必要があるのか​​ わかりません。

カスタム属性:

Public Class AtLeastOneRequiredAttribute
Inherits ValidationAttribute
Implements IClientValidatable

Private ReadOnly _properties As String()

Public Sub New(ByVal properties As String())
    _properties = properties
End Sub

Protected Overrides Function IsValid(value As Object, validationContext As ValidationContext) As ValidationResult
    If IsNothing(_properties) Or _properties.Length < 1 Then
        Return Nothing
    End If

    For Each prop In _properties
        Dim propertyInfo = validationContext.ObjectType.GetProperty(prop)
        If IsNothing(propertyInfo) Then
            Return New ValidationResult(String.Format("unknown property {0}", prop))
        End If

        Dim propertyValue = propertyInfo.GetValue(validationContext.ObjectInstance, Nothing)
        If TypeOf propertyValue Is String AndAlso Not String.IsNullOrEmpty(propertyValue.ToString) Then
            Return Nothing
        End If

        If Not IsNothing(propertyValue) Then
            Return Nothing
        End If
    Next

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

Public Function GetClientValidationRules(metadata As ModelMetadata, context As ControllerContext) As IEnumerable(Of ModelClientValidationRule) Implements IClientValidatable.GetClientValidationRules
    Dim result = New List(Of ModelClientValidationRule)
    Dim rule As New ModelClientValidationRule
    rule.ErrorMessage = ErrorMessage
    rule.ValidationType = "atleastonerequired"

    rule.ValidationParameters("properties") = String.Join(",", _properties)

    result.Add(rule)

    Return result
End Function
End Class

モデル:

<AtLeastOneRequired({"FieldA", "FieldB", "FieldC"}, ErrorMessage:="Testing")> _
Public Property FieldA As String
Public Property FieldB As String
Public Property FieldC As String

意見:

<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>
jQuery.validator.unobtrusive.adapters.add(
    'atleastonerequired', ['properties'], function (options) {
        options.rules['atleastonerequired'] = options.params;
        options.messages['atleastonerequired'] = options.message;
    }
);

jQuery.validator.addMethod('atleastonerequired', function (value, element, params) {
    var properties = params.properties.split(',');
    var values = $.map(properties, function (property, index) {
        var val = $('#' + property).val();
        return val != '' ? val : null;
    });
    return values.length > 0;
}, '');


@Using Html.BeginForm("Results", "List")
@Html.ValidationSummary(False)
    @<div>
        @Html.LabelFor(Function(model) model.FieldA)
        @Html.EditorFor(Function(model) model.FieldA)
    </div>
    @<div>
        @Html.LabelFor(Function(model) model.FieldB)
        @Html.EditorFor(Function(model) model.FieldB)
    </div>
    @<div>
        @Html.LabelFor(Function(model) model.FieldC)
        @Html.EditorFor(Function(model) model.FieldC)
    </div>
    @<p>
        <input type="submit" value="Search" />
    </p>
End Using
4

1 に答える 1

1

上記のコードは実際に機能しますが、デモ用にコードを単純化しようとしましたが、そこにバグがありました。学んだ教訓。

実際のビュー コード:

@<div class="ui-widget">
    @Html.LabelFor(Function(model) model.CategoryID)
    <input class="text-box single-line" id="Category" name="Category" type="text" value="" />
</div>
@<div class="ui-widget">
    @Html.LabelFor(Function(model) model.Manufacturer)
    @Html.EditorFor(Function(model) model.Manufacturer)
</div>
@<div>
    @Html.LabelFor(Function(model) model.aModel)
    @Html.EditorFor(Function(model) model.aModel)
</div>

実際のモデル:

<Display(Name:="Category")> _
<AtLeastOneRequired({"CategoryID", "Manufacturer", "aModel"}, ErrorMessage:="Testing")> _
Public Property CategoryID As String
Public Property Manufacturer As String
<Display(Name:="Model")> _
Public Property aModel As String

以前、私はjQuery AutocompleteHTML Helpersをいじっていました.. CategoryID次に、カスタム属性をプロパティに割り当てました。AtLeastOneRequried属性をManufacturerorのような別のプロパティに移動するとModel、機能しました。

HTML ヘルパーを使用してカスタム属性をプロパティに関連付けることを忘れないでください。そうしないと、ソース コードで正しくレンダリングされません。

于 2013-05-03T20:43:38.157 に答える