We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Cascade populate dropdown on Add/Edit Mode with Dialog Template

Hi guys,

I'm doing my first project on ASP.NET MVC using your grid and I need a bit of your help. I'm basing my development on the great examples you have online on Help and Demos sections.

I'm blocked and need an example with a grid with Datasource Adaptor = UrlAdaptor, EditMode=DialogTemplate with a cascade dropdownlist (selecting a value from Item0 ddl-filled when opening add/edit dialog-, fills Item1 dll using a call to the server based on Item0 selection) and also two dropdownlist more that are related to Main Item (Item2 and Item3).
I attached this images to explain a bit clear what I need:

ER Diagram

Grid


Dialog Template


Also, would it be possible to have a tab container on Add/Edit Template Dialog where first tab has what image shows and another tab with other fields related to MainItem?

Thanks in advance, I'll be waiting for your answer.

Best regards,
 Chama.


5 Replies

JK Jayaprakash Kamaraj Syncfusion Team April 1, 2016 12:00 PM UTC

Hi Gustavo,

Thanks for contacting Syncfusion support.

Query1: need an example with a grid with Datasource Adaptor = UrlAdaptor, EditMode=DialogTemplate with a cascade dropdownlist

We have created a Grid sample with UrlAdaptor and DialogTemplate. We have used actionComplete event and changed event for cascading dropdown. ActionComplete event triggers every complete actions in grid. Please refer to the following code example, help documentation and sample.

GridFeatures.cshtml

@(Html.EJ().Grid<object>("FlatGrid")

                        .Datasource(ds => ds.URL(Url.Action("/DataSource")).UpdateURL(Url.Action("/DialogUpdate")).InsertURL(Url.Action("/DialogInsert")).RemoveURL(Url.Action("/DialogDelete")).Adaptor(AdaptorType.UrlAdaptor))

        .AllowScrolling()

         .AllowPaging()    /*Paging Enabled*/

                 .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.DialogTemplate).DialogEditorTemplateID("#template"); })

              .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).TextAlign(TextAlign.Right).ValidationRules(v => v.AddRule("required", true).AddRule("number", true)).Width(90).Add();

            col.Field("CustomerID").HeaderText("Customer ID").Width(90).EditType(EditingType.Dropdown).Add();

            col.Field("ShipCity").HeaderText("Ship City").Width(90).EditType(EditingType.Dropdown).Add();

        }).ClientSideEvents(eve=>eve.ActionComplete("complete")))

<script type="text/template" id="template">

    <b>Order Details</b>

    <div id="defaultTab" style="width: 500px;height:300px;">

        <ul>

            <li><a rel='nofollow' href="#tab1">Tab1</a></li>

            <li><a rel='nofollow' href="#tab2">Tab2</a></li>

        </ul>

        <div id="tab1" width="200px">

              <img src="../Content/ej/web/common-images/6.png"  />

        </div>

        <div id="tab2">

            <table cellspacing="10">

                <tr>

                    <td style="text-align: right;">

                        Order ID

                    </td>

                    <td style="text-align: left">

                        <input id="OrderID" name="OrderID" value="{{: OrderID}}" disabled="disabled" class="e-field e-ejinputtext valid e-disable"

                               style="text-align: right; width: 116px; height: 28px" />

                    </td>

                 

                </tr>

                <tr>

                    <td style="text-align: right;">

                        Customer ID

                    </td>

                    <td style="text-align: left">

                        <span class="txt">Select Group</span>

                        <input id="CustomerID" type="text" />

                    </td>

                    </tr>

                <tr>

                    <td style="text-align: right;">

                        Ship City

                    </td>

                    <td style="text-align: left">

                        <span class="txt">Select Country</span>

                        <input id="ShipCity" type="text" />

                    </td>

                    </tr>

                  

            </table>

        </div>

        </div>

</script>

<script type="text/javascript">

        function complete(args) {

            if ((args.requestType == "beginedit" || args.requestType == "add") && args.model.editSettings.editMode == "dialogtemplate") {

                $("#defaultTab").ejTab({ selectedItemIndex: 0 });

                var groups = [

          { parentId: 'a', text: "Group A" },

          { parentId: 'b', text: "Group B" },

          { parentId: 'c', text: "Group C" },

          { parentId: 'd', text: "Group D" },

          { parentId: 'e', text: "Group E" }]

                //first level child

                var countries = [{ value: "Algeria", parentId: 'a', text: "Algeria", sprite: "flag-dz" },

               { value: "Armenia", parentId: 'a', text: "Armenia", sprite: "flag-am" },

….

               { value: "Ukraine", parentId: 'e', text: "Ukraine", sprite: "flag-ua" }]

                $('#CustomerID').ejDropDownList({

                    dataSource: groups,

                    fields: { value: "parentId", text: "text" },

                    cascadeTo: 'ShipCity',

                    change: "onChange",

                    width: "100%"

                });

                $('#ShipCity').ejDropDownList({

                    dataSource: countries,

                                      width: "100%"

                });

                if (args.requestType == "beginedit") {

                    $("#OrderID").attr("disabled", "disabled");

                }

            }

        }

        function onChange() {

            var ctry = $('#ShipCity').data("ejDropDownList");

            ctry.element.val("");

        }
</script>
GridFeatures.cs

        public ActionResult DataSource(Syncfusion.JavaScript.DataManager dm)

        {

            var DataSource = OrderRepository.GetAllRecords();

            DataResult result = new DataResult();

            result.result = DataSource.Skip(dm.Skip).Take(dm.Take).ToList();

            result.count = DataSource.Count();

            return Json(result, JsonRequestBehavior.AllowGet);

        }

        public class DataResult

        {

            public IEnumerable result { get; set; }

            public int count { get; set; }

        }


        public ActionResult DialogUpdate(EditableOrder value)

        {

            OrderRepository.Update(value);

            var data = OrderRepository.GetAllRecords();

            return Json(value, JsonRequestBehavior.AllowGet);

        }


        public ActionResult DialogInsert(EditableOrder value)

        {

            OrderRepository.Add(value);

            var data = OrderRepository.GetAllRecords();

            return Json(value, JsonRequestBehavior.AllowGet);

        }


        public ActionResult DialogDelete(int key)

        {

            OrderRepository.Delete(key);

            var data = OrderRepository.GetAllRecords();

            return Json(data, JsonRequestBehavior.AllowGet);
        }


Help documentation: http://help.syncfusion.com/js/api/ejgrid#events:actioncomplete

Sample: http://www.syncfusion.com/downloads/support/forum/123570/ze/SyncfusionMvcApplication65-1511282556

Query2: would it be possible to have a tab container on Add/Edit Template Dialog where first tab has what image shows and another tab with other fields related to MainItem?

We have achieved your requirement using actionComplete event. This event triggers every complete actions in grid. Please refer to the following code example and screenshot.

<script type="text/template" id="template">

    <b>Order Details</b>

    <div id="defaultTab" style="width: 500px;height:300px;">

        <ul>

            <li><a rel='nofollow' href="#tab1">Tab1</a></li>

            <li><a rel='nofollow' href="#tab2">Tab2</a></li>

        </ul>

        <div id="tab1" width="200px">

         @*Do your tab1 operations here*@

              <img src="../Content/ej/web/common-images/6.png"  />

        </div>

        <div id="tab2">

            @*Do your tab2 operations here*@

            <table cellspacing="10">

                <tr>

                    <td style="text-align: right;">

                        Order ID

                    </td>

                    <td style="text-align: left">

                        <input id="OrderID" name="OrderID" value="{{: OrderID}}" disabled="disabled" class="e-field e-ejinputtext valid e-disable"

                               style="text-align: right; width: 116px; height: 28px" />

                    </td>

                 

                </tr>

                <tr>

                    <td style="text-align: right;">

                        Customer ID

                    </td>

                    <td style="text-align: left">

                        <span class="txt">Select Group</span>

                        <input id="CustomerID" type="text" />

                    </td>

                    </tr>

                <tr>

                    <td style="text-align: right;">

                        Ship City

                    </td>

                    <td style="text-align: left">

                        <span class="txt">Select Country</span>

                        <input id="ShipCity" type="text" />

                    </td>

                    </tr>

                  

            </table>

        </div>

        </div>
</script>

<script type="text/javascript">

        function complete(args) {

            if ((args.requestType == "beginedit" || args.requestType == "add") && args.model.editSettings.editMode == "dialogtemplate") {

                $("#defaultTab").ejTab({ selectedItemIndex: 0 });


            }

        }
</script>




Regards,

Jayaprakash K.



UN Unknown Syncfusion Team April 1, 2016 06:28 PM UTC

Hi Jayaprakas,

Thanks for your help.

The code and sample you post really help me, but I'm  having problems when inserting and updating: the selection of the dropdowns is not been sent to the model.

I show you part of the code:

View:

  @(Html.EJ().Grid <Models.OrderTable> ("Grid")
        .Datasource(ds => ds.URL("GetDeviceData")
                            .InsertURL("PerformInsert")
                            .UpdateURL("PerformUpdate")
                            .RemoveURL("PerformDelete")
                            .Adaptor(AdaptorType.UrlAdaptor)
                            )
        .AllowPaging()
        .AllowSorting()
        .AllowMultiSorting()
        .SortSettings(sort =>
        {
            sort.SortedColumns(col => col.Field("Id").Add());
            sort.SortedColumns(col => col.Field("Nickname").Add());
            sort.SortedColumns(col => col.Field("Model.Value").Add());
        })
        .EditSettings(e => e.AllowEditing()
                            .AllowDeleting()
                            .AllowAdding()
                            .EditMode(EditMode.DialogTemplate)
                            .DialogEditorTemplateID("#template")
                                )
        .ToolbarSettings(tool => tool.ShowToolbar().ToolbarItems(item =>
        {
            item.AddTool(ToolBarItems.Add);
            item.AddTool(ToolBarItems.Edit);
            item.AddTool(ToolBarItems.Delete);
            item.AddTool(ToolBarItems.Update);
            item.AddTool(ToolBarItems.Cancel);
        }))

        .Columns(col =>
        {
            col.Field("Id").HeaderText("Id").IsPrimaryKey(true).TextAlign(TextAlign.Left).Width(40).Add();
            col.Field("Nickname").HeaderText("Nickname").TextAlign(TextAlign.Left).Width(50).Add();
            col.Field("ModelId").Visible(false).Add();
            col.Field("Model.Value").HeaderText("Model").TextAlign(TextAlign.Left).Width(50).Add();
        })
         .ClientSideEvents(eve =>
         {
             eve.ActionComplete("complete");

         }))
         
    <script type="text/template" id="template">
        <div id="defaultTab" style="width: 500px;height:500px;">
            <ul>
                <li><a rel='nofollow' href="#tab1">General</a></li>
                <li><a rel='nofollow' href="#tab2">Details</a></li>
                <li><a rel='nofollow' href="#tab3">Login information</a></li>
            </ul>
            <div id="tab1" width="200px">
                <table cellspacing="10">
                    <tr>
                        <td style="text-align: right;">
                            Nickname
                        </td>
                        <td style="text-align: left">
                            <input id="Nickname" name="Nickname" value="{{: Nickname}}" class="e-field e-ejinputtext valid"
                                   style="text-align: right; width: 116px; height: 28px" />
                        </td>
                    </tr>
                    <tr>
                        <td style="text-align: right;">
                            Manufacturer
                        </td>
                        <td style="text-align: left">
                            <select id="Manufacturer" name="Manufacturer"></select>
                        </td>
                    </tr>
                    <tr>
                        <td style="text-align: right;">
                            Model
                        </td>
                        <td style="text-align: left">
                            <select id="Model" name="Model"></select>
                        </td>
                    </tr>
                   
                </table>
            </div>
            <div id="tab2">
                <table cellspacing="10">
                    ...
                </table>
            </div>
                <table cellspacing="10">
                    <tr>
                        <td style="text-align: right;">
                            IP Address
                        </td>
                        <td style="text-align: left">
                            <input id="Login_IPAddress" name="Login_IPAddress" value="{{: Login_IPAddress}}" class="e-field e-ejinputtext valid"
                                   style="text-align: right; width: 116px; height: 28px" />
                        </td>
                    </tr>
                    <tr>
                        <td style="text-align: right;">
                            Username
                        </td>
                        <td style="text-align: left">
                            <input id="Login_Username" name="Login_Username" value="{{: Login_Username}}" class="e-field e-ejinputtext valid"
                                   style="text-align: right; width: 116px; height: 28px" />
                        </td>
                    </tr>
                    <tr>
                        <td style="text-align: right;">
                            Password
                        </td>
                        <td style="text-align: left">
                            <input id="Login_Password" name="Login_Password" value="{{: Login_Password}}" class="e-field e-ejinputtext valid"
                                   style="text-align: right; width: 116px; height: 28px" />
                        </td>
                    </tr>
                    <tr>
                        <td style="text-align: right;">
                            Enable Password
                        </td>
                        <td style="text-align: left">
                            <input id="Login_EnablePassword" name="Login_EnablePassword" value="{{: Login_EnablePassword}}" class="e-field e-ejinputtext valid"
                                   style="text-align: right; width: 116px; height: 28px" />
                        </td>
                    </tr>
                </table>
            </div>
        </div>
</script>
    <script type="text/javascript">

        function complete(args) {
            if ((args.requestType == "beginedit" || args.requestType == "add") && args.model.editSettings.editMode == "dialogtemplate") {
                $("#defaultTab").ejTab({ selectedItemIndex: 0 });

                var manufacturers = JSON.parse('@Html.Raw(ViewBag.Manufacturers)');
                var models = JSON.parse('@Html.Raw(ViewBag.Models)');
              
                $('#Manufacturer').ejDropDownList({
                    dataSource: manufacturers,
                    fields: { value: "parentId", text: "text" },
                    cascadeTo: 'Model',
                    change: "onChange",
                    width: "100%"
                });

                $('#Model').ejDropDownList({
                    dataSource: models,
                    width: "100%"
                });

                $("#Model").ejDropDownList("setSelectedValue", args.row.children().eq(2).text());

            }
        }

        function onChange() {
            var ctry = $('#Model').data("ejDropDownList");
            ctry.element.val("");
        }
    </script>

Controller:

Controller:
public ActionResult Index()
        {
            ViewBag.Manufacturers = JsonConvert.SerializeObject(ManufacturerList);
            ViewBag.Models = JsonConvert.SerializeObject(ModelList);
            return View();
        }

        //Provide grid datasource
        public ActionResult GetDeviceData()
        {
            var result = _deviceService.GetAll().ToList();
            return Json(new { result = result, count = result.Count }, JsonRequestBehavior.AllowGet);
        }

        //Perform file insertion
        public ActionResult PerformInsert(EditParams param)
        {
            _deviceService.Create(param.value);
            return RedirectToAction("GetDeviceData");
        }

        //Perform update
        public ActionResult PerformUpdate(EditParams param)
        {
            _deviceService.Update(param.value);
            return RedirectToAction("GetDeviceData");
        }

        //Perform delete
        public ActionResult PerformDelete(long key, string keyColumn)
        {

            var device = _deviceService.GetById(key);
            _deviceService.Delete(device);
            return RedirectToAction("GetDeviceData");
        }   
       
        public IEnumerable<object> ManufacturerList
        {
            get
            {
                var manufacturerList = _manufacturerService.GetAll();
                var type = new List<object>();
                foreach (var manufacturerItem in manufacturerList)
                {
                    type.Add(new { parentId = manufacturerItem.Id, text = manufacturerItem.Value });
                }

                return type;
            }
        }
       
        public IEnumerable<object> ManufacturerList
        {
            get
            {
                var manufacturerList = _manufacturerService.GetAll();
                var type = new List<object>();
                foreach (var manufacturerItem in manufacturerList)
                {
                    type.Add(new { parentId = manufacturerItem.Id, text = manufacturerItem.Value });
                }

                return type;
            }
        }
       
        public IEnumerable<object> ModelList
        {
            get
            {
                var modelList = _modelService.GetAll();
                var type = new List<object>();
                foreach (var modelItem in modelList)
                {
                    type.Add(new { value = modelItem.Id, parentId = modelItem.ManufacturerId, text = modelItem.Value });
                }

                return type;
            }
        }



UN Unknown Syncfusion Team April 1, 2016 06:33 PM UTC

Models:

Models:

public class EditParams
    {
        //Paging Params
        public int skip { get; set; }
        public int take { get; set; }

        //Grid Action Params
        public string action { get; set; }
        public int key { get; set; }
        public string keyColumn { get; set; }
        public Model.Device value { get; set; }

        //Batch Edit Params
        public IEnumerable<OrderTable> added { get; set; }
        public IEnumerable<OrderTable> changed { get; set; }
        public IEnumerable<OrderTable> deleted { get; set; }
    }

and

    [Table("Devices")]
    public class Device : AuditableEntity<long>
    {
        [Required]
        [MaxLength(50)]
        [Display(Name = "Nickname")]
        public string Nickname { get; set; }

        [Display(Name = "Model")]
        public int ModelId { get; set; }

        [ForeignKey("ModelId")]
        public virtual Model Model { get; set; }
    }

The problem is that I'm not receiving the value on Model dropdown and SaveChanges fails.

What I'm doing wrong? Something that I'm missing to associate dropdown value with model field?

Thanks in advance.

Regards,
 Gustavo.


UN Unknown Syncfusion Team April 2, 2016 12:06 AM UTC

Hi,

The issue was that dropdown has a different name that the model's field it should match (Dropdown name = Model, model's field= ModelId), my mistake.

You do a great job guys with Support Forum (code snippets, functional examples, etc), keep working this way!

Best regards,
 Gustavo.


JK Jayaprakash Kamaraj Syncfusion Team April 4, 2016 06:55 AM UTC

Hi Gustavo, 


We are happy that the provided suggestion helped you. 

Please get back to us if you need any further assistance.  


Regards, 


Jayaprakash K.


Loader.
Up arrow icon