Apply Select2 directive to dynamic DropDownList using AngularJS in ASP.Net MVC

Last Reply 9 months ago By dharmendr

Posted 9 months ago

Hi,

Based upon below url

Display record on HTML Table based upon dynamic control values using AngularJS in ASP.Net MVC

I am going to do 2 functionalities

1) I have applied select2 directive to dropdowns it was working properly at dropdowns (in screenshot only first fields are dropdowns)

probelm is that it select textbox is displaying at other fields also

it was disturbing the remaining fields also

https://ibb.co/ypTdSjP

please look at into screenshot 

2) I am fetching dropdowns values everything dynamically

As per requirement i am going  to add one static value(All)

Including Dynamic values i need to Display this static value along with relevant dropdown values

If i can select All value in dropdown then assign it value to '%' or else assign to relevant value

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.full.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
app.directive("select2", function ($timeout, $parse) {
    return {
        restrict// Code goes here
    : 'AC',
        require: 'ngModel',
        link: function (scope, element, attrs) {
            console.log(attrs);
            $timeout(function () {
                element.select2();
                element.select2Initialized = true;
            });
 
            var refreshSelect = function () {
                if (!element.select2Initialized) return;
                $timeout(function () {
                    element.trigger('change');
                });
            };
 
            var recreateSelect = function () {
                if (!element.select2Initialized) return;
                $timeout(function () {
                    element.select2('destroy');
                    element.select2();
                });
            };
 
            scope.$watch(attrs.ngModel, refreshSelect);
 
            if (attrs.ngOptions) {
                var list = attrs.ngOptions.match(/ in ([^ ]*)/)[1];
                // watch for option list change
                scope.$watch(list, recreateSelect);
            }
 
            if (attrs.ngDisabled) {
                scope.$watch(attrs.ngDisabled, refreshSelect);
            }
        }
    };
});

 

Posted 9 months ago Modified on 9 months ago

Hi mahesh213,

Refer below code.

Controller

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

    [HttpGet]
    public ActionResult GetReportNames()
    {
        TestEntities db = new TestEntities();
        var coun = db.Report1.Select(model => new { model.RId, model.RName }).ToList();
        return Json(coun, JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public JsonResult getAll(int Id)
    {
        TestEntities db = new TestEntities();
        List<Details> employeeList = (from E in db.ReportSettings
                                        where E.RId == Id
                                        orderby E.RSId
                                        select new Details
                                        {
                                            RSId = E.RSId,
                                            RId = E.RId,
                                            CName = E.CName,
                                            CType = E.CType,
                                            ValueCName = E.ValueCName,
                                            DisplayCName = E.DisplayCName,
                                            FromTable = E.FromTable,
                                            Date = E.Date
                                        }).ToList();
        foreach (Details details in employeeList)
        {
            if (details.CType.ToLower() == "dropdown")
            {
                var coun = db.ReportSettings.Where(x => x.CType == details.CType && x.RId == details.RId && x.RSId == details.RSId).ToList();
                string fromTable = coun[0].FromTable;
                string displayCName = coun[0].DisplayCName;
                string valueCName = coun[0].ValueCName;
                // Generate dynamic query.
                string query = "SELECT " + displayCName + " AS Text," + valueCName + " AS Value FROM " + fromTable;
                // Execute dynamic query.
                SqlConnection con = new SqlConnection();
                string connectionstring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                con.ConnectionString = connectionstring;
                SqlCommand cmd = new SqlCommand(query, con);
                con.Open();
                SqlDataReader sdr = cmd.ExecuteReader();
                List<SelectListItem> values = new List<SelectListItem>();
                // Adding option ALL to DropDownList.
                values.Add(new SelectListItem
                {
                    Text = "All",
                    Value = "%"
                });
                while (sdr.Read())
                {
                    values.Add(new SelectListItem
                    {
                        Text = sdr["Text"].ToString(),
                        Value = sdr["Value"].ToString()
                    });
                }
                con.Close();
                // Adding options for DropDownList.
                details.DDLValues = values;
            }
            else if (details.CType.ToLower() == "datepicker")
            {
                // Settting DatePicker value to display default text.
                switch (details.Date.ToLower())
                {
                    case "today":
                        details.Date = DateTime.Now.ToString("yyyy-MM-dd");
                        break;
                    case "yesterday":
                        details.Date = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                        break;
                    default:
                        break;
                }
            }
        }

        return Json(employeeList, JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public JsonResult PopulateTable(Detail values)
    {
        TestEntities db = new TestEntities();
        // Getting the query from Report1 table.
        string query = db.Report1.Where(x => x.RId == values.RId).Select(x => x.RQuery).FirstOrDefault();
        for (int i = 0; i < values.details.Count; i++)
        {
            string key = "{" + values.details[i].Text + "}";
            string value = "'" + values.details[i].Value + "'";
            // Replace the place holder with value.
            query = query.Replace(key, value);
        }
        // Execute your final query and return json result and bind the gridview on success function.
        // Your code to return json.
        return Json(null, JsonRequestBehavior.AllowGet);
    }

    public class Detail
    {
        public int RId { get; set; }
        public List<SelectListItem> details { get; set; }
    }

    public class Details
    {
        public int RSId { get; set; }
        public int? RId { get; set; }
        public string CName { get; set; }
        public string CType { get; set; }
        public string ValueCName { get; set; }
        public string DisplayCName { get; set; }
        public string FromTable { get; set; }
        public string Date { get; set; }
        public List<SelectListItem> DDLValues { get; set; }
    }
}

View

<html>
<head>
    <title>Index</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" />
    <script type="text/javascript">
        var app = angular.module("MyApp", []);
        app.directive("select2", function ($timeout, $parse) {
            return {
                restrict// Code goes here
                : 'AC',
                require: 'ngModel',
                link: function (scope, element, attrs) {
                    console.log(attrs);
                    $timeout(function () {
                        if ($(element).eq(0).text().toLowerCase() != 'select') {
                            element.select2();
                            element.select2Initialized = true;
                        }
                    });

                    var refreshSelect = function () {
                        if (!element.select2Initialized) return;
                        $timeout(function () {
                            element.trigger('change');
                        });
                    };

                    var recreateSelect = function () {
                        if (!element.select2Initialized) return;
                        $timeout(function () {
                            element.select2('destroy');
                            element.select2();
                        });
                    };
                    scope.$watch(attrs.ngModel, refreshSelect);

                    if (attrs.ngOptions) {
                        var list = attrs.ngOptions.match(/ in ([^ ]*)/)[1];
                        // watch for option list change
                        scope.$watch(list, recreateSelect);
                    }

                    if (attrs.ngDisabled) {
                        scope.$watch(attrs.ngDisabled, refreshSelect);
                    }
                }
            };
        });
        app.controller("MyControll", ['$scope', '$http', '$filter', function ($scope, $http, $filter) {
            GetReportName();
            function GetReportName() {
                $scope.reports = [];
                $http({
                    method: 'Get',
                    url: '/Home/GetReportNames'
                }).success(function (data, status, headers, config) {
                    $scope.reports = data;
                }).error(function (data, status, headers, config) {
                    $scope.message = 'Unexpected Error';
                });
            }

            $scope.Change = function () {
                var Id1 = $scope.RName;
                if (Id1 != null) {
                    $http({
                        method: 'POST',
                        url: '/Home/getAll/',
                        params: { Id: Id1 }
                    }).success(function (data, status, headers, config) {
                        for (var i = 0; i < data.length; i++) {
                            if (data[i].Date != null) {
                                data[i].Date = new Date(data[i].Date);
                            }
                        }
                        $scope.items = data;
                    }).error(function (data, status, headers, config) {
                        $scope.items = 'Unexpected Error';
                    });
                }
            }

            function ConvertDate(d) {
                var parts = d.split(" ");
                var months = { Jan: "01", Feb: "02", Mar: "03", Apr: "04", May: "05", Jun: "06", Jul: "07", Aug: "08", Sep: "09", Oct: "10", Nov: "11", Dec: "12" };
                return parts[3] + "/" + months[parts[1]] + "/" + parts[2];
            }
            $scope.Save = function () {
            }
        } ]);
    </script>
</head>
<body ng-app="MyApp" ng-controller="MyControll">
    <div class="container">
        <div id="wrapper" class="clearfix">
            <form name="userForm" novalidate>
            <h4 class="modal-title" style="text-align: center;">
                Report Details
            </h4>
            <div class="form-horizontal">
                <div class="form-row">
                    <div class="col-md-4">
                        <label for="RName">
                            ReportName
                        </label>
                        <select class="form-control" id="RName" select2="" ng-model="RName" containercssclass="all"
                            ng-options="c.RId as c.RName for c in reports" ng-disabled="disabled" ng-change="Change()">
                            <option value="">Select Name</option>
                        </select>
                    </div>
                </div>
            </div>
            </form>
        </div>
        <br />
        <div class="well">
            <div ng-repeat="report in items">
                <div class="row">
                    <div class="col-md-2">
                        <label for="RNo">
                            {{report.CName}}
                        </label>
                    </div>
                    <div class="col-md-3">
                        <%--Dynamic Controls display based on CType Start--%>
                        <select class="form-control ApplySelect" ng-model="report.FromTable" ng-show="report.CType.toLowerCase()=='dropdown'"
                            ng-options="c.Text as c.Text for c in report.DDLValues" select2>
                            <option value="">Select</option>
                        </select>
                        <input type="date" class="form-control" ng-model="report.Date" ng-show="report.CType.toLowerCase()=='datepicker'" />
                        <input type="text" class="form-control" ng-model="report.ValueCName" ng-show="report.CType.toLowerCase()=='textbox'" />
                        <%--Dynamic Controls display based on CType End--%>
                    </div>
                </div>
            </div>
            <input type="button" value="Save" ng-click="Save()" />
        </div>
    </div>
</body>
</html>

Screenshot