Angular JS和ASP服务器端控制验证

时间:2016-03-11 03:58:07

标签: asp.net angularjs validation server-side validationsummary

我正在使用angular JS for asp.net服务器端控件

<div class="gridpage mb40" name="myForm" ng-model="myForm" ng-form
   <div class="form-group">
      <label class="">Name of the Supplier:</label>
        <asp:TextBox ID="txtSupName" CssClass="form-control" runat="server" ng-model="txtSupName" name="txtName" required></asp:TextBox>
        <p ng-show="myForm.txtName.$invalid && !myForm.txtName.$pristine" class="help-block">Your Name is Required.</p>
   </div>
 </div>

问题是在运行时我部署我的代码,为服务器端控件命名属性更改,所以我无法呈现错误消息的段落 有没有其他方法可以访问控件而不是myform.txtName。$ invalid ??

尝试使用clientIDmode= Static,它会保持id静态,但名称仍会更改,

1 个答案:

答案 0 :(得分:2)

尝试此解决方案jsfiddle

创建一个指令alias,它存储对ngModelController的引用,该引用独立于输入的name(asp:TextBox)。

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope, $log) {

  })
  .directive('alias', function() {
    return {
      restrict: "A",
      require: "ngModel",
      scope: {
        alias: "="
      },
      link: function(scope, elem, attr, ngModel) {
        scope.alias = ngModel;
      }
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <form name="myForm">
      <input name="txtName" ng-model="txtName" required alias="aliasName" ng-pattern="/^[0-9]+$/">
      <div ng-if="myForm.txtName.$error.required">Name is reauired by name</div>
      <div ng-if="aliasName.$error.required">Name is reauired by alias</div>
      <div ng-if="myForm.txtName.$error.pattern">Invalid pattern by name</div>
      <div ng-if="aliasName.$error.pattern">Invalid pattern by alias</div>
      <br>
      <pre>myForm.txtName.$error = {{myForm.txtName.$error|json}}</pre>
      <pre>aliasName.$error = {{aliasName.$error|json}}</pre>
    </form>
  </div>
</div>