Dynamically assign ng-maxlength from Database in AngularJS and ASP.Net MVC

Last Reply 7 months ago By dharmendr

Posted 7 months ago

Hi,
https://www.aspforums.net/Threads/173488/Maximum-Length-and-Required-validation-for-TextBox-and-DropDownList-in-AngularJS/

If we can look at into above example we are

assigning ng-maxlength value statically

I need to fetch that value from database instead

of giving static

For that I am creating one more database with

relevant fields

STI_Name-100

STI_Code_20

STI_GstCode-3

I need to assign above fields values to relevant

fields at form

Ex: ng-maxlength=10 (static) -don't need

Ng-maxlength= (dynamic)

My self is didn't get any idea

Could you please check properly and help me

Posted 7 months ago

Hi mahesh213,

Refer below sample code.

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        return View();
    }

    public int GetMaxLength()
    {
        // Get MaxLength from Database.
        int maxLength = 10;
        return maxLength;
    }
}

View

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.0/css/bootstrap.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript">
    var app = angular.module("MyApp", []);
    app.controller("MyController", ['$scope', '$http', function ($scope, $http) {
        $http.get("/Home/GetMaxLength").then(function (r) {
            $scope.maxLength = r.data;
        }, function (r) { });
    } ]);
</script>
<div ng-app="MyApp" ng-controller="MyController">
    <div class="container">
        <form name="userForm" novalidate>
        <div class="form-horizontal">
            <div class="row">
                <div class="col-md-4">
                    <input type="text" class="form-control" name="Name" ng-model="Name" ng-minlength="3"
                        ng-maxlength="{{maxLength}}" placeholder="Enter Name" required />
                </div>
                <div class="col-md-4">
                    <span style="color: red" ng-show="userForm.Name.$error.required && !userForm.Name.$pristine" class="help-block">State is required.</span> 
                    <span style="color: red" ng-show="userForm.Name.$error.minlength">Name is too short.</span> 
                    <span style="color: red" ng-show="userForm.Name.$error.maxlength">Name should be maximum of {{maxLength}} characters.</span>
                </div>
            </div>
        </div>
        </form>
    </div>
</div>

Screenshot