Angular JS验证复杂的ASP.NET MVC对象

时间:2014-09-18 13:51:51

标签: javascript asp.net asp.net-mvc angularjs asp.net-mvc-4

我尝试使用AngularJS在子窗体中验证我的模型,但错误信息未显示,并且该按钮始终处于禁用状态。

<form novalidate>

    ... Some other form fields

    <ng-form name="SearchPostcodeForm">
        <div class="partial-search-postcode-service form-horizontal">
            <div class="form-group">
                <label
                    class="control-label col-md-2"
                    for="CustomerAddressDetails_CurrentAddress_SearchPostcode">
                    Post code
                </label>
                <div class="col-sm-6 col-xs-10">
                    <input
                        id="CustomerAddressDetails_CurrentAddress_SearchPostcode"
                        name="CustomerAddressDetails.CurrentAddress.SearchPostcode"
                        ng-model="CustomerAddress.CurrentAddress.SearchPostcode"
                        required="required" type="text" >
                    <small ng-show="SearchPostcodeForm.CustomerAddress_CurrentAddress_SearchPostcode.$error.required">
                        Your postcode is required.
                    </small>
                </div>
            </div>
            <input type="submit" value="Find your address"
                name="action:Current_SearchPostcode"
                data-val-valgroup-name="SearchPostcode"
                class="btn btn-primary causesvalidation"
                ng-click="seachPostcode($event, 'Current');"
                ng-disabled="SearchPostcodeForm.$invalid"
                disabled="disabled">
        </div>
    </ng-form>

    ... Some other form fields

</form>

修改SearchPostCode中的值会更新类,因此验证本身似乎正在发生。

例如:

<ng-form name="SearchPostcodeForm" novalidate="" class="ng-pristine ng-invalid ng-invalid-required">

变为:

<ng-form name="SearchPostcodeForm" novalidate="" class="ng-dirty ng-valid ng-valid-required">

但是永远不会显示错误消息,并且按钮从未启用。

我在这里缺少什么?这是表单字段的真正长名称的问题吗?或者我应该使用id? (&#39;。&#39;分隔符可能导致问题?)

1 个答案:

答案 0 :(得分:1)

在这里重读之后......我已经指着id而不是名字了(显然这是错的)。

此外,因为我的表单名称有&#39;。&#39;其中的分隔符,我需要稍微不同地访问它。

<small
    ng-show="SearchPostcodeForm['CustomerAddressDetails.CurrentAddress.SearchPostcode'].$error.required">
    Your postcode is required.
</small>

工作示例: http://plnkr.co/edit/cgUlYEGubYcfDh80YqsI

现在一切正常。