Populate KendoGrid column based on KendoDropDownList selection using jQuery in ASP.Net MVC

mahesh213
 
on Oct 24, 2021 11:32 PM
Sample_674582.zip
810 Views

Hi,

In url code in Get Customers Method I have added one more new Field Population.

[Solved] ASP.Net MVC AngularJS KendoGrid toolbar create Error: Uncaught ReferenceError: CountryId is not defined

Population Field coming based upon StateId.

public JsonResult GetPopulations1(int state)
{
    string populations = "";
    if (state == 4)
    {
        populations = "4848848448";
    }
    else if (state == 5)
    {
        populations = "544848848";
    }
    else if (state == 6)
    {
        populations = "3444444";
    }
    else
    {
        populations = "";
    }

    return Json(populations, JsonRequestBehavior.AllowGet);
}

In view populate population value based upon State

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Oct 25, 2021 06:28 AM
on Oct 26, 2021 05:17 AM

Hi mahesh213,

Refer below code.

Controller

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

    public JsonResult GetCustomers()
    {
        List<Customer> customers = new List<Customer>();
        customers.Add(new Customer { Id = 1, Name = "John Hammond", CountryId = 1, StateId = 1, Population = "0" });
        customers.Add(new Customer { Id = 2, Name = "Mudassar Khan", CountryId = 2, StateId = 4, Population = "4848848448" });
        customers.Add(new Customer { Id = 3, Name = "Suzanne Mathews", CountryId = 3, StateId = 8, Population = "0" });
        customers.Add(new Customer { Id = 4, Name = "Robert Schidner", CountryId = 1, StateId = 3, Population = "0" });
        return Json(customers, JsonRequestBehavior.AllowGet);
    }

    public JsonResult GetCountryName()
    {
        List<Country> countries = new List<Country>();
        countries.Add(new Country { CountryId = 1, Name = "USA" });
        countries.Add(new Country { CountryId = 2, Name = "India" });
        countries.Add(new Country { CountryId = 3, Name = "Canada" });
        return Json(countries, JsonRequestBehavior.AllowGet);
    }

    public JsonResult GetStateName()
    {
        List<State> states = new List<State>();
        states.Add(new State { StateId = 1, Name = "Alabama", CountryId = 1 });
        states.Add(new State { StateId = 2, Name = "Arizona", CountryId = 1 });
        states.Add(new State { StateId = 3, Name = "Alaska", CountryId = 1 });
        states.Add(new State { StateId = 4, Name = "Maharashtra", CountryId = 2 });
        states.Add(new State { StateId = 5, Name = "Gujarat", CountryId = 2 });
        states.Add(new State { StateId = 6, Name = "Goa", CountryId = 2 });
        states.Add(new State { StateId = 7, Name = "Ontario", CountryId = 3 });
        states.Add(new State { StateId = 8, Name = "Quebec", CountryId = 3 });
        states.Add(new State { StateId = 9, Name = "Manitoba", CountryId = 3 });
        return Json(states, JsonRequestBehavior.AllowGet);
    }

    public JsonResult UpdateCustomer(Customer customer)
    {
        return Json(customer, JsonRequestBehavior.AllowGet);
    }

    public JsonResult AddCustomer(Customer customer)
    {
        return Json(customer, JsonRequestBehavior.AllowGet);
    }

    public JsonResult GetPopulations(int state)
    {
        string populations = "";
        if (state == 4)
        {
            populations = "4848848448";
        }
        else if (state == 5)
        {
            populations = "544848848";
        }
        else if (state == 6)
        {
            populations = "3444444";
        }
        else
        {
            populations = "";
        }

        return Json(populations, JsonRequestBehavior.AllowGet);
    }

    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int CountryId { get; set; }
        public int StateId { get; set; }
        public string Population { get; set; }
    }

    public class Country
    {
        public int CountryId { get; set; }
        public string Name { get; set; }
    }

    public class State
    {
        public int StateId { get; set; }
        public string Name { get; set; }
        public int CountryId { get; set; }
    }
}

View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.1.114/styles/kendo.default-v2.min.css" />
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript" src="https://kendo.cdn.telerik.com/2020.1.114/js/angular.min.js"></script>
    <script type="text/javascript" src="https://kendo.cdn.telerik.com/2020.1.114/js/kendo.all.min.js"></script>
    <script type="text/javascript">
        var app = angular.module("MyApp", ["kendo.directives"]);
        app.controller("MyController", function ($scope) {
            GetCountries();
            GetStates();
            $scope.mainGridOptions = {
                dataSource: {
                    transport: {
                        read: { url: "/Home/GetCustomers" },
                        update: { url: "/Home/UpdateCustomer" }
                    },
                    schema: {
                        model: {
                            id: "Id",
                            fields: {
                                Id: { editable: false, nullable: true, type: "number" },
                                Name: { editable: true, nullable: true, type: "string" },
                                CountryId: { editable: true, nullable: true, type: "number" },
                                StateId: { editable: true, nullable: true, type: "number" },
                                Population: { editable: true, nullable: true, type: "number" }
                            }
                        }
                    },
                    pageSize: 4,
                    serverPaging: false,
                    serverSorting: false
                },
                toolbar: ["create"],
                editable: "inline",
                sortable: true,
                pageable: true,
                resizeable: true,
                columns: [
                    { field: "Id", title: "Id", width: "70px" },
                    { field: "Name", title: "Name", width: "150px" },
                    {
                        title: "Country",
                        field: "CountryId",
                        width: "200px",
                        template: "#= CountryName(CountryId) #",
                        editor: function (container, options) {
                            var input = $('<input id="CountryId" name="' + options.field + '" />');
                            input.appendTo(container);
                            input.kendoDropDownList({
                                autoBind: false,
                                dataTextField: "Name",
                                dataValueField: "CountryId",
                                dataSource: Countries
                            }).appendTo(container);
                        }
                    },
                    {
                        title: "State",
                        field: "StateId",
                        width: "200px",
                        template: "#= GetStateName(StateId) #",
                        editor: function (container, options) {
                            var input = $('<input id="StateId" name="' + options.field + '" />');
                            input.appendTo(container);
                            input.kendoDropDownList({
                                dataTextField: "Name",
                                dataValueField: "StateId",
                                cascadeFrom: "CountryId",
                                dataSource: States,
                                dataBound: function (e) {
                                    var ddl = e.sender;
                                    var row = $(ddl.element).closest("tr");
                                    var stateId = $(row).find('[id*=StateId]').val();
                                    var lblPopulation = $(row).find("[id=lblPopulation]");
                                    SetPopulation(lblPopulation, stateId);
                                }
                            }).appendTo(container);
                        }
                    },
                    {
                        title: "Population",
                        field: "Population",
                        width: "200px",
                        editor: function (container, options) {
                            $('<span id="lblPopulation"></span>').appendTo(container);
                        }
                    },
                    {
                        title: 'Action',
                        command: [{ name: "edit", text: "Edit", iconClass: "k-icon k-i-hyperlink-open" }]
                    }
                ]
            };
        })

        $(function () {
            $('body').on('change', "[id*=StateId]", function () {
                var stateId = $(this).closest('tr').find("input[id=StateId]").val();
                var lblPopulation = $(this).closest('tr').find("[id=lblPopulation]");
                SetPopulation(lblPopulation, stateId);
            });
        });

        var Countries = [];
        var States = [];
        function GetCountries() {
            $.ajax({
                method: 'Get',
                url: '/Home/GetCountryName',
            }).success(function (data) {
                Countries = data;
            }).error(function (response) {
                alert(response.responseText);
            });
        }

        function SetPopulation(lblPopulation, stateId) {
            var obj = { state: stateId };
            $.ajax({
                method: 'POST',
                url: '/Home/GetPopulations',
                data: JSON.stringify(obj),
                dataType: "json",
                contentType: "application/json; charset=utf-8"
            }).success(function (data) {
                $(lblPopulation).html(data);
            }).error(function (response) {
                alert(response.responseText);
            });
        }

        function GetStates() {
            $.ajax({
                method: 'Get',
                url: '/Home/GetStateName',
            }).success(function (data) {
                States = data;
            }).error(function (data) {
                message = 'Unexpected Error';
            });
        }

        function CountryName(countryId) {
            for (var i = 0; i < Countries.length; i++) {
                if (Countries[i].CountryId == countryId) {
                    return Countries[i].Name;
                }
            }
        }

        function GetStateName(stateId) {
            for (var i = 0; i < States.length; i++) {
                if (States[i].StateId == stateId) {
                    return States[i].Name;
                }
            }
        }
    </script>
</head>
<body ng-app="MyApp" ng-controller="MyController">
    <kendo-grid k-options="mainGridOptions" id="tblCustomers"></kendo-grid>
</body>
</html>

Screenshot