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

Last Reply one year ago By dharmendr

Posted one year ago


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




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 one year ago

Hi mahesh213,

Refer below sample code.


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

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


<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) { });
    } ]);
<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 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>