Bind grid dropdownlist column with ajax

I must be doing something wrong when I want to bind grid foreign key column with ajax call.
First, I have initial fill in the controller:

var potpr = from p in db.Proizvod
                            join pp in db.ProizvodPod on p.ProizvodID equals pp.ProizvodID
                            where p.ProizvodID == 5
                            orderby pp.Naziv
                            select new
                            {
                                pp.ProizvodPodID,
                                pp.Naziv
                            };
ViewBag.dsPotproizvodi = potpr.ToList();

And after that, my grid looks like this:

@(Html.EJ().Grid<object>("gridPP")
                            .Datasource((IEnumerable<object>)ViewBag.dsPolicaPP)
                            .AllowSelection(true)
                            .AllowResizing()
                            .AllowSorting(true)
                            .Locale("hr-HR")
                            .EditSettings(edit => { edit.AllowAdding().AllowDeleting().ShowDeleteConfirmDialog().AllowEditing(); })
                            .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("PolicaProPodID").HeaderText("PolicaProPodID").IsPrimaryKey(true).Visible(false).TextAlign(TextAlign.Right).Width(75).Add();
                            col.Field("ProizvodPodID").HeaderText("Potproizvod").ForeignKeyField("ProizvodPodID").ForeignKeyValue("Naziv").EditType(EditingType.Dropdown).DataSource((IEnumerable<object>)ViewBag.dsPotproizvodi).Width(80).Add();
                        col.Field("NetoPremija").HeaderText("Premija").TextAlign(TextAlign.Right).Width(75).Format("{0:N2}").Add();
                    }).ClientSideEvents(eve => eve.ActionComplete("actionComplete"))
                )

And when I start the project, everything is working fine. Saving data in grid is ok.






But, when I want to change grid dropdownlist column Potproizvod based on the field above the grid, I'm facing this.

First, I set actionComplete function in javascript:

function actionComplete(args) {
        //while editing the grid
        if ((args.requestType == "beginedit") || (args.requestType == "add")) {
            var dropdownObj = $("#ProizvodID").ejDropDownList('instance');
            var src = '@Url.Action("GetPotproizvodi", "Policas", new { area = "" })';
            var prID = dropdownObj.model.value;

            $.ajax({
                cache: false,
                url: src,
                data: { "ProizvodID": prID },
                type: "get",
            }).done(function (data) {
                $("#gridPPProizvodPodID").ejDropDownList({ dataSource: data, fields: { text: "Naziv", value: "ProizvodPodID" } }); //Set the new Dropdown datasource
            }).fail(function (xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                alert(err.Message);
            });
        }
    }

And then the action in the controller to get the data:

[HttpGet]
        [OutputCache(Duration = 1)]
        public JsonResult GetPotproizvodi(int? ProizvodID)
        {
            var potpr = (from pr in db.Proizvod
                        join pp in db.ProizvodPod on pr.ProizvodID equals pp.ProizvodID
                        where pr.ProizvodID == ProizvodID
                        orderby pp.Naziv
                        select new
                        {
                            pp.ProizvodPodID,
                            pp.Naziv
                        }).ToList();

            return Json(potpr, JsonRequestBehavior.AllowGet);
        }

Then I start the project, my dropdownlist column has the right values, based on Proizvod field


But when I want to save the data in grid, there is no value in the column



Is there some help for this?
Thanks!

Bernard.

7 Replies

PK Prasanna Kumar Viswanathan Syncfusion Team August 13, 2018 01:02 PM UTC

Hi Bernard, 

Thanks for contacting Syncfusion support. 

In your code example we found that in actionComplete event you are modifying the dataSource only for the ejDropDownList not for the column dataSource. Based on the column dataSource(ForeignKeyField) the value will be updated in Grid. So, we suspect that it will be root cause of the issue and we also suggest you to modify the column dataSource once the value gets updated in the actionBegin event of Grid. 

Refer the below code example 

@(Html.EJ().Grid<object>("gridPP") 
                            .Datasource((IEnumerable<object>)ViewBag.dsPolicaPP) 
                       .                        .                     .                       .                   .                       . 
                            }).ClientSideEvents(eve => eve.ActionComplete("actionComplete").ActionBegin("begin")) 
) 
 
</div> 
<script type="text/javascript"> 
    var ddldata = @Html.Raw(Json.Encode(ViewBag.ddldata)) 
    function actionComplete(args) { 
        //while editing the grid 
.                        .                    .                  .                      .                 .  
        } 
    } 
    function begin(args){ 
        if (args.requestType == "save") { 
            var Obj = $("#gridPP").ejGrid("instance"); 
            Obj.model.columns[1].dataSource = ddldata; 
        } 
    } 
</script> 

For your convenience we have prepared a sample which can be downloaded from below link 


Please get back to us if you have further queries.  

Regards, 
Prasanna Kumar N.S.V 
 



BJ Bernard Jurlina August 14, 2018 06:46 AM UTC

Hi Prasanna!

Thank you for your help. My grid now showing the right value after I select something from dropdownlist.
But, now I have one more situation. Basically, I want something like this: User opens up the page, then he can add/remove/change data in the grid, and on submit, I'm passing grids datasource to post controller action and save it's data to the database. Passing grids datasource and saving in the controller is ok, but look what I get after adding some values in the grid:

This is ok, after I choose Proizvod, the datasource of dropdownlist and column in the grid has changed, and grid saves it ok.



But when I want to edit, for example, the first row I added:



Potproizvod is not selected, and the Premija column value is 2, but I saved 1.

Thank you!
Bernard.


MP Manivannan Padmanaban Syncfusion Team August 15, 2018 11:07 AM UTC

Hi Bernard,

 

Query 1: Potproizvod is not selected,

 

In your case we have updated the dropdownlist value by using ajax action in the actionComplete event. So, while editing begins the datasource  becomes null. Due to this, while editing the Potproizvod is not selected.

 

Query 2: The Premija column value is 2, but I saved 1.

 

We are unable to reproduce the reported issue. Please refer the attached link for video demo and sample.

 

Regards,

Manivannan Padmanaban.


Attachment: demosample_ad1f2e6b.7z


BJ Bernard Jurlina August 21, 2018 05:36 AM UTC

Hi Manivannan!

I downloaded your example and if I made a little modification for DataSource1 in the controller, like this:

public ActionResult GridFeatures()
        {
            var DataSource1 = new NorthwindDataContext().OrdersViews.Where(o => o.City == "Zagreb").ToList();
            ViewBag.dsPolicaPP = DataSource1;
            employee.Add(new Employee(1, "AO1"));
            employee.Add(new Employee(2, "AO2"));
            employee.Add(new Employee(3, "AO3"));
            employee.Add(new Employee(4, "AO4"));
            var DataSource2 = employee;
            ViewBag.dsPotproizvodi = DataSource2;
            employee1.Add(new Employee(5, "PP1"));
            employee1.Add(new Employee(6, "PP2"));
            employee1.Add(new Employee(7, "PP3"));
            employee1.Add(new Employee(8, "PP4"));
            ViewBag.ddldata = employee1;
            return View();
        }

because I want to simulate empty grid for my project. Then, after entering two rows



the grid displays ok, but when I want to edit the first row


I got the wrong value in the column Premija.

Thanks!
Bernard.


VN Vignesh Natarajan Syncfusion Team August 22, 2018 11:19 AM UTC

Hi Bernard, 
 
Thanks for the update. 
 
We have analyzed your query and we are able to reproduce the reported issue (once records were added, not able to edit first record). For editing IsPrimaryKey must be enabled for any of the available columns and it must be unique value. Based on the Primarykey value are records will be edited or deleted.  
 
Refer the below code example 
 
        col.Field("OrderID").HeaderText("PolicaProPodID").IsPrimaryKey(true).Visible(false).TextAlign(TextAlign.Right).Width(75).Add(); 
                                      
 
 
In the sample provided we have enabled IsPrimaryKey for OrderID column which is hidden state. Initially you are binding empty data and while adding value for OrderID(PrimaryKey) is passed as null since it is not visible. So, every time you add a records, primaryKey value will be null. So the reported issue occur. 
Now we suggest you to pass unique value to PrimaryKey column while adding a record in the actionBegin event of ejGrid. Refer the below code example 
 
function begin(args) { 
 
        if (args.requestType == "save") { 
            args.rowData.OrderID = Math.random() // pass random value to primarycolumn while saving 
            var Obj = $("#gridPP").ejGrid("instance"); 
            Obj.model.columns[1].dataSource = ddldata; 
        } 
    } 
     
 
For your convenience we have modified the provided sample which can be downloaded from below link 
 
Refer our Knowledge base document for your importance of PrimaryKey while editing 
 
 
Regards, 
Vignesh Natarajan 



BJ Bernard Jurlina August 23, 2018 07:44 PM UTC

Hi Vignesh!

Math.random() is the right answer. Now, everything is ok when I want to edit saved row.

Thanks!
Bernard.


PK Prasanna Kumar Viswanathan Syncfusion Team August 24, 2018 05:54 AM UTC

Hi Bernard, 
 
We are happy to hear that your issue has been solved. 
 
Please get back to us if you need any further assistance. 
 
Regards, 
Prasanna Kumar N.S.V 


Loader.
Up arrow icon