Articles in this section
Category / Section

How to render cascading dropdown while editing in ASP.NET MVC Grid?

7 mins read

In certain cases, changing the dataSource of one dropdown on selecting a value from other dropdown is known as the cascading effect. This effect can be applied to two dropdown controls within ASP.NET MVC Grid upon editing that is explained in detail in this document.

Solution

The following example explains in detail on how to achieve the cascading effect in Grid for two ForeignKey columns that refreshes the dataSource of one dropdown based on the value selected in another dropdown.

Example

  1. Render the Grid control.

HTML:

<div id="Grid"></div>

 

Javascript:

<script>
    var data = @Html.Raw(Json.Encode(ViewBag.designation))
    var data1 = @Html.Raw(Json.Encode(ViewBag.country))
 
    $(function () {
        $("#Grid").ejGrid({
            // the datasource "window.gridData" is referred from 'http://js.syncfusion.com/demos/web/scripts/jsondata.min.js'
            dataSource: window.gridData,
            allowPaging:true,
            editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true},
            toolbarSettings: { showToolbar: true, toolbarItems: ["add", "edit", "delete", "update", "cancel"] },
            actionComplete:"Complete",
            columns: [
                { field: "OrderID", headerText: 'OrderID', isPrimaryKey: true, width: 75 },
                { field: "EmployeeID", headerText: 'EmployeeID', width: 75 },
                { field: "CustomerID", headerText: 'Designation', foreignKeyField: "CustomerID", foreignKeyValue: "Designation", dataSource: data, width: 75 },
                { field: "ShipCity", headerText: 'Country', foreignKeyField: "ShipCity", foreignKeyValue: "country", dataSource: data1, width: 75 }
            ]
        });
    });
</script>

 

C#

namespace EJGrid.Controllers
{
    public class HomeController : Controller
    {
        public static List<Orders> order = new List<Orders>();
        public static List<Customers> customer = new List<Customers>();
        public static List<Country> city = new List<Country>();
        public ActionResult Index()
        {
            BindDataSource();
            ViewBag.datasource = order;
            ViewBag.designation = customer;
            ViewBag.country = city;
            return View();
        }     
        public ActionResult DataSource(string designation)
        {
            var userTemplates = city.Where(c => c.Designation == designation).Distinct().ToList();
            var data = new List<object>();
            foreach (var Cust in userTemplates)
            {
                data.Add(new { value = Cust.ShipCity, text = Cust.country });
            }
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        private void BindDataSource()
        {
            int code = 10000;
            for (int i = 1; i < 10; i++)
            {
                order.Add(new Orders(code + 1, "ALFKI", i + 2, 2.3 * i, "Berlin", "Germany"));
                order.Add(new Orders(code + 2, "ANATR", i + 0, 3.3 * i, "Madrid", "Spain"));
                order.Add(new Orders(code + 3, "ANTON", i + 4, 4.3 * i, "Cholchester", "UK"));
                order.Add(new Orders(code + 4, "BLONP", i + 1, 5.3 * i, "Marseille", "France"));
                order.Add(new Orders(code + 5, "BOLID", i + 3, 6.3 * i, "Tsawassen", "Canada"));
                code += 5;
            }
            customer.Add(new Customers("ALFKI", "Sales Rep"));
            customer.Add(new Customers("ANATR", "Admin"));
            customer.Add(new Customers("ANTON", "Manager"));
            customer.Add(new Customers("BLONP", "Representative"));
            customer.Add(new Customers("BOLID", "Assistant Manager"));
 
            city.Add(new Country("Berlin", "Sales Rep", "India"));
            city.Add(new Country("Madrid", "Admin", "USA"));
            city.Add(new Country("Cholchester", "Manager", "Russia"));
            city.Add(new Country("Marseille", "Representative", "Australia"));
            city.Add(new Country("Tsawassen", "Assistant Manager", "UK"));
            }  }
       }

 

 

 

MVC

RAZOR:

@(Html.EJ().Grid<object>("Grid")
                .Datasource(((IEnumerable<object>)ViewBag.datasource))
                .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing(); })
                .AllowPaging()
                .ToolbarSettings(toolbar =>
                {
                    toolbar.ShowToolbar().ToolbarItems(items =>
                    {
                        items.AddTool(ToolBarItems.Add);
                        items.AddTool(ToolBarItems.Edit);
                        items.AddTool(ToolBarItems.Delete);
                        items.AddTool(ToolBarItems.Update);
                        items.AddTool(ToolBarItems.Cancel);
                    });
                })
                .Columns(col =>
                {
                    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width(75).Add();
                    col.Field("EmployeeID").HeaderText("Employee ID").Width(75).Add();                      col.Field("CustomerID").HeaderText("Designation").ForeignKeyField("CustomerID").ForeignKeyValue("Designation").DataSource(((IEnumerable<object>)ViewBag.designation)).Width(75).Add();//Dropdownlist based on which the Country column dropdown is refreshed                   col.Field("ShipCity").HeaderText("Country").ForeignKeyField("ShipCity").ForeignKeyValue("country").DataSource(((IEnumerable<object>)ViewBag.country)).Width(75).Add();//Refreshed upon change in Designation Column
                })
                .ClientSideEvents(eve => eve.ActionComplete("Complete")
                ))

 

C#

namespace EJGrid.Controllers
{
    public class HomeController : Controller
    {
        public static List<Orders> order = new List<Orders>();
        public static List<Customers> customer = new List<Customers>();
        public static List<Country> city = new List<Country>();
        public ActionResult Index()
        {
            BindDataSource();
            ViewBag.datasource = order;
            ViewBag.designation = customer;
            ViewBag.country = city;
            return View();
        }     
        public ActionResult DataSource(string designation)
        {
            var userTemplates = city.Where(c => c.Designation == designation).Distinct().ToList();
            var data = new List<object>();
            foreach (var Cust in userTemplates)
            {
                data.Add(new { value = Cust.ShipCity, text = Cust.country });
            }
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        private void BindDataSource()
        {
            int code = 10000;
            for (int i = 1; i < 10; i++)
            {
                order.Add(new Orders(code + 1, "ALFKI", i + 2, 2.3 * i, "Berlin", "Germany"));
                order.Add(new Orders(code + 2, "ANATR", i + 0, 3.3 * i, "Madrid", "Spain"));
                order.Add(new Orders(code + 3, "ANTON", i + 4, 4.3 * i, "Cholchester", "UK"));
                order.Add(new Orders(code + 4, "BLONP", i + 1, 5.3 * i, "Marseille", "France"));
                order.Add(new Orders(code + 5, "BOLID", i + 3, 6.3 * i, "Tsawassen", "Canada"));
                code += 5;
            }
            customer.Add(new Customers("ALFKI", "Sales Rep"));
            customer.Add(new Customers("ANATR", "Admin"));
            customer.Add(new Customers("ANTON", "Manager"));
            customer.Add(new Customers("BLONP", "Representative"));
            customer.Add(new Customers("BOLID", "Assistant Manager"));
 
            city.Add(new Country("Berlin", "Sales Rep", "India"));
            city.Add(new Country("Madrid", "Admin", "USA"));
            city.Add(new Country("Cholchester", "Manager", "Russia"));
            city.Add(new Country("Marseille", "Representative", "Australia"));
            city.Add(new Country("Tsawassen", "Assistant Manager", "UK"));
            }  }
       }

 

ASP.NET

<ej:Grid ID="FlatGrid" runat="server" AllowPaging="true">
           <EditSettings AllowEditing="true" AllowAdding="true" AllowDeleting="true"></EditSettings>
           <ToolbarSettings ShowToolbar="true" ToolbarItems="add,edit,delete,update,cancel"></ToolbarSettings>
           <ClientSideEvents ActionComplete="Complete" />
           <Columns>
                <ej:Column Field="OrderID" HeaderText="OrderID" IsPrimaryKey="true" Width="75"/>
                <ej:Column Field="EmployeeID" HeaderText="EmployeeID" Width="75"/>
                <ej:Column Field="CustomerID" HeaderText="Designation" ForeignKeyField="CustomerID" ForeignKeyValue="Designation" Width="75"/>               
                <ej:Column Field="ShipCity" HeaderText=”Country" ForeignKeyField="ShipCity" ForeignKeyValue="country" Width="75" />
           </Columns> 
           </ej:Grid> 

 

C#

namespace WebApplication21
{
    public partial class _Default : Page
    {
 
        public static List<Orders> order = new List<Orders>();
        public static List<Customers> customer = new List<Customers>();
        public static List<Country> city = new List<Country>();        
        protected void Page_Load(object sender, EventArgs e)
        {
            BindDataSource();
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static object DataSource(string designation)
        {
            var userTemplates = city.Where(c => c.Designation == designation).Distinct().ToList();
            var data = new List<object>();
            foreach (var Cust in userTemplates)
            {
                data.Add(new { value = Cust.ShipCity, text = Cust.country });
            }
            return data;
        }
        private void BindDataSource()
        {
            int code = 10000;
            for (int i = 1; i < 10; i++)
            {
                order.Add(new Orders(code + 1, "ALFKI", i + 2, 2.3 * i, "Berlin", "Germany"));
                order.Add(new Orders(code + 2, "ANATR", i + 0, 3.3 * i, "Madrid", "Spain"));
                order.Add(new Orders(code + 3, "ANTON", i + 4, 4.3 * i, "Cholchester", "UK"));
                order.Add(new Orders(code + 4, "BLONP", i + 1, 5.3 * i, "Marseille", "France"));
                order.Add(new Orders(code + 5, "BOLID", i + 3, 6.3 * i, "Tsawassen", "Canada"));
                code += 5;
            }
            this.FlatGrid.DataSource = order;
            this.FlatGrid.DataBind();
 
            customer.Add(new Customers("ALFKI", "Sales Rep"));
            customer.Add(new Customers("ANATR", "Admin"));
            customer.Add(new Customers("ANTON", "Manager"));
            customer.Add(new Customers("BLONP", "Representative"));
            customer.Add(new Customers("BOLID", "Assistant Manager"));
 
            var index = this.FlatGrid.Columns.FindIndex(col => col.Field == "CustomerID");
            this.FlatGrid.Columns.ElementAt(index).DataSource = customer;
 
 
            city.Add(new Country("Berlin", "Sales Rep","India"));
            city.Add(new Country("Madrid", "Admin","USA"));
            city.Add(new Country("Cholchester", "Manager","Russia"));
            city.Add(new Country("Marseille", "Representative","Australia"));
            city.Add(new Country("Tsawassen", "Sales Rep","UK"));
           
 
            var index1 = this.FlatGrid.Columns.FindIndex(col => col.Field == "ShipCity");
            this.FlatGrid.Columns.ElementAt(index1).DataSource = city;
        }

ASP.NET CORE

HTML

<ej-grid id="FlatGrid" datasource="ViewBag.datasource" action-complete="Complete">
    <e-edit-settings allow-adding="true" allow-editing="true" allow-deleting="true"></e-edit-settings>
    <e-toolbar-settings show-toolbar="true" toolbar-items='@new List<string> {"add","edit","update","cancel"}' />
    <e-columns>
        <e-column field="OrderID" header-text="OrderID" width="75" is-primary-key="true"></e-column>
        <e-column field="EmployeeID" header-text="EmployeeID" width="75"></e-column>
        <e-column field="CustomerID" header-text="Designation" foreign-key-field="CustomerID" foreign-key-value="Designation" datasource="ViewBag.designation" width="75"></e-column>
        <e-column field="ShipCity" header-text="Country" foreign-key-field="ShipCity" foreign-key-value="country" datasource="ViewBag.country" width="75"></e-column>
    </e-columns>
</ej-grid>

C#

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public static List<Orders> order = new List<Orders>();
        public static List<Customers> customer = new List<Customers>();
        public static List<Country> city = new List<Country>();
        public IActionResult Index()
        {
            BindDataSource();
            ViewBag.datasource = order;
            ViewBag.designation = customer;
            ViewBag.country = city;
            return View();
        }
        public ActionResult DataSource(string designation)
        {
            var userTemplates = city.Where(c => c.Designation == designation).Distinct().ToList();
            var data = new List<object>();
            foreach (var Cust in userTemplates)
            {
                data.Add(new { value = Cust.ShipCity, text = Cust.country });
            }
            return Json(data);
        }
        private void BindDataSource()
        {
            int code = 10000;
            for (int i = 1; i < 10; i++)
            {
                order.Add(new Orders(code + 1, "ALFKI", i + 2, 2.3 * i, "Berlin", "Germany"));
                order.Add(new Orders(code + 2, "ANATR", i + 0, 3.3 * i, "Madrid", "Spain"));
                order.Add(new Orders(code + 3, "ANTON", i + 4, 4.3 * i, "Cholchester", "UK"));
                order.Add(new Orders(code + 4, "BLONP", i + 1, 5.3 * i, "Marseille", "France"));
                order.Add(new Orders(code + 5, "BOLID", i + 3, 6.3 * i, "Tsawassen", "Canada"));
                code += 5;
            }
 
            customer.Add(new Customers("ALFKI", "Sales Rep"));
            customer.Add(new Customers("ANATR", "Admin"));
            customer.Add(new Customers("ANTON", "Manager"));
            customer.Add(new Customers("BLONP", "Representative"));
            customer.Add(new Customers("BOLID", "Assistant Manager"));
 
            city.Add(new Country("Berlin", "Sales Rep", "India"));
            city.Add(new Country("Madrid", "Admin", "USA"));
            city.Add(new Country("Cholchester", "Manager", "Russia"));
            city.Add(new Country("Marseille", "Representative", "Australia"));
            city.Add(new Country("Tsawassen", "Assistant Manager", "UK"));
        } }
}

ANGULAR

HTML

<ej-grid id="Grid" #grid [dataSource]="datasource" [toolbarSettings]="toolbarItems" [editSettings]="editSettings" (actionComplete)="Complete($event)" >
    <e-columns>
        <e-column field="OrderID"  headerText="OrderID" isPrimaryKey="true" width="75"></e-column>
        <e-column field="EmployeeID" headerText="EmployeeID" width="75" ></e-column>
        <e-column field="CustomerID" headerText="Designation" width="75" foreignKeyField= "CustomerID" foreignKeyValue= "Designation" [dataSource]= "data"></e-column>           
        <e-column field="ShipCity" headerText="Country" width="75" foreignKeyField= "ShipCity" foreignKeyValue= "country" [dataSource]= "data1"></e-column>             
    </e-columns>
</ej-grid>

TS

import {Component, ViewEncapsulation,ViewChild} from '@angular/core';
 
import {CommonModule} from "@angular/common";
 
import { EJComponents } from "ej-angular2/src/ej/core";
 
@Component({
    selector: 'ej-app',
    templateUrl: 'src/grid/grid.component.html',
})
export class GridComponent {
  public datasource;
  public editSettings;
  public toolbarItems;
  public data;
  public data1;
 
  @ViewChild('grid') grid: EJComponents<any, any>;
  constructor() {
    //The datasource "window.gridData" is referred from 'http://js.syncfusion.com/demos/web/scripts/jsondata.min.js'
          this.datasource = [
                   {OrderID:10001,EmployeeID:1,CustomerID:"ALFKI",ShipCity:"Berlin"},
                   {OrderID:10001,EmployeeID:1,CustomerID:"ALFKI",ShipCity:"Berlin"},
                   {OrderID:10002,EmployeeID:2,CustomerID:"ANATR",ShipCity:"Madrid"},
                   {OrderID:10003,EmployeeID:3,CustomerID:"BOLID",ShipCity:"Cholchester"},
                   {OrderID:10004,EmployeeID:4,CustomerID:"ANATR",ShipCity:"Tsawassen"},
                   {OrderID:10005,EmployeeID:5,CustomerID:"ANTON",ShipCity:"Berlin"},
                   {OrderID:10006,EmployeeID:6,CustomerID:"ALFKI",ShipCity:"Cholchester"},
                   {OrderID:10007,EmployeeID:7,CustomerID:"BLONP",ShipCity:"Marseille"},
                   {OrderID:10008,EmployeeID:8,CustomerID:"BOLID",ShipCity:"Tsawassen"}
                                   ];
 
          this.editSettings = { allowEditing: true, allowAdding: true, allowDeleting: true, showDeleteConfirmDialog: true};
 
          this.toolbarItems = { showToolbar : true, toolbarItems : ["add", "edit", "delete", "update", "cancel"]};
 
          this.data = [
                         {CustomerID:"ALFKI",Designation:"Sales Rep"},
                         {CustomerID:"ANATR",Designation:"Admin"},
                         {CustomerID:"ANTON",Designation:"Manager"},
                         {CustomerID:"BLONP",Designation:"Representative"},
                        {CustomerID:"BOLID",Designation:"Assistant Manager"}];
     this.data1 = [
                          {ShipCity:"Berlin",Designation:"Sales Rep",country:"India"},
                          {ShipCity:"Madrid",Designation:"Admin",country:"USA"},
                          {ShipCity:"Cholchester",Designation:"Manager",country:"Russia"},
                          {ShipCity:"Marseille",Designation:"Representative",country:"Australia"},
                          {ShipCity:"Tsawassen",Designation:"Assistant Manager",country:"UK"}
                          ];
  }
 
  Complete(args: any) { 
    if (args.requestType == "beginedit" || args.requestType == "add") {
        $("#GridCustomerID").ejDropDownList({ change: function(e){
            $.ajax({
                url: 'http://localhost:49449/Home/Datasource',
                type: 'GET',
                data: { "designation": e.text },//pass the selectedValue of the dropdown to server side
                success: function (data1) {
                    $("#GridShipCity").ejDropDownList({ dataSource: data1 });//assign the filtered dataSource obtained from serverSide
                    $("#GridShipCity").ejDropDownList({ selectedIndex: 0 });
                }
            })
        } });//bind the change event to dropdown
        if (args.requestType == "beginedit") {
            var titleObj = $("#GridCustomerID").data("ejDropDownList");//get the edited dropdown object
            titleObj.selectItemByValue(args.rowData.CustomerID);
            $.ajax({
                url: 'http://localhost:49449/Home/Datasource',
                type: 'GET',
                data: { "designation": titleObj.getSelectedValue() },//passed the selectedValue of the dropdown to server side
                success: function (data1) {
                    $("#GridShipCity").ejDropDownList({ dataSource: data1, selectedItemIndex: 0 });//assign the filtered dataSource obtained from serverSide
                }
            })
        }
    }
}
}

 

2. In the ActionComplete events of the Grid, the ValChange function is bound to the Change event of the ejDropDownList. The selected value of the Designation dropdown is passed to the server side on the Ajax call, getting the filtered data from the server side and assigning it to the Country dropdown’s dataSource.

<script type="text/javascript">    
    function Complete(args) {
        if (args.requestType == "beginedit" || args.requestType == "add") {
            $("#GridCustomerID").ejDropDownList({ change: "ValChange" });//bind the change event to dropdown
            if (args.requestType == "beginedit") {
                var titleObj = $("#GridCustomerID").data("ejDropDownList");//get the edited dropdown object
                $.ajax({
                    url: 'Home/DataSource',
                    type: 'GET',
                    data: { "designation": titleObj.selectedTextValue},//passed the selectedValue of the dropdown to server side
                    success: function (data1) {
                        $("#GridShipCity").ejDropDownList({ dataSource: data1 ,selectedItemIndex:0  });//assign the filtered dataSource obtained from serverSide
                    }
                })
            }
        }
    } 
</script> 
  1. In the change event of the Designation dropdown, the selected value of the Designation dropdown is passed to the server side on the Ajax call, getting the filtered data from the server side and assigning it to the Country dropdown’s dataSource.
        //change event of the Designation dropdown.
        function ValChange(e) {
            $.ajax({
                url: 'Home/DataSource',
                type: 'GET',
                data: { "designation": e.text },//pass the selectedValue of the dropdown to server side
                success: function (data1) {
                    $("#GridShipCity").ejDropDownList({ dataSource: data1, selectedItemIndex: 0 });//assign the filtered dataSource obtained from serverSide
                }
            })        
        }
    

Result:

Graphical user interface, table

Figure 1Initial rendering of grid

 

 

Graphical user interface, application, table

Figure 2On editing a record

 

A screenshot of a computer

Figure 3On changing the value of designation column


Conclusion

I hope you enjoyed learning about how to render cascading dropdown while editing in ASP.NET MVC Grid.

You can refer to our ASP.NET MVC Grid page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET MVC Grid example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please sign in to leave a comment
Access denied
Access denied