1

Trying to render the Json returned data to kendo drop down list, but not rendering. Please find the code snippett. I am able to see the alert box. I tried JSON.parse(siteNameData), but no luck.

AJAX CALL

$.ajax({
    url: '../Report/GetSitesofSelectedClient',
    type: "GET",
    cache: false,
    datatype: "json",
    data: { "selectedClientCode": selectedClientCode },
    contentType: "application/json",
    async: false,
    success: function(siteNameData) {
        alert('hello');

        $("#siteNamesDropDown").kendoDropDownList({
            dataTextField: "text",
            dataValueField: "value",
            template: $("#CheckboxTemplate2").html(),
            datasource: siteNameData,
            placeholder: "Select...",
            select: function(e) {
                e.preventDefault();
            }
        }).data("kendoDropDownList");

        //PopulateSiteNamesDropDown(siteNamesReceived);
     },
     error: function(xhr, ajaxOptions, thrownError) {
         ShowDialogError(xhr, 'High Chart Status Report');
     }
});

CONTROLLER

    public JsonResult GetSitesofSelectedClient(string selectedClientCode)
    {
        ViewBag.ShowReport = true;

        var highChartModel = new HighChartViewModel();

        var siteData = highChartModel.GetListOfSites(selectedClientCode);

        return Json(new {siteData}, JsonRequestBehavior.AllowGet);

    }

MODEL

 public string GetListOfSites(string clientCode)
 {

         SiteNameList = _serviceSessionManager.GetSiteListForClient(clientCode);

        listOfSiteNames = new List<SiteStatusReportModel>();

        foreach (Site siteName in SiteNameList)
        {
            var siteNameInfo = new SiteStatusReportModel
            {
                text     = siteName.SiteName,
                value    = siteName.SiteCode,
                selected = false
            };

            listOfSiteNames.Add(siteNameInfo);
        }

        var siteNameJsonData = JsonHelper.ToJsonString(listOfSiteNames)
        return siteNameJsonData;
 }

3 Answers 3

2

you don't reinitialize the drop down every time. Initialize it only once. On your controller build a List and return that through json. To reset the dropdown you need to set the datasource like this

var combobox = $("#siteNamesDropDown").data('kendoDropDownList');
if(combobox != null){
    //set the datasource of the combo
    combobox.dataSource.data(siteNameData);
    //requery the drop down so it shows the new data
    combobox.dataSource.query();
    //reset the selected value
    combobox.value("");
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Matt. 1). I need to append everytime the json returned data to the console. In this case what i needs to do. 2). I needs to remove some of the items from the existing dropdown. 3). If the datasource is null what i needs to do. ie, sometimes json data is [].
this code is for after the drop down has been initialized. we do that on page load. Setting the datasource and doing the .query above will clear the old data. It shouldn't matter if the datasource was null since you are setting it here
Thanks Matt. After initialization and when try to get the data and if the list is empty i am getting the error. How I can avoid that.
if what you are returning is empty then I would put an if(siteNameData != ""){ around the code above so it will only fire if there is something in it. see what is being returned when empty and check on that could be "", null, undefined
Thanks Matt. Working fine. As you said everytime when json data is returned I was initializing. Saved my day.
0

Did you console.log(siteNameData)? Is it returning a proper json? May be the resonse is inisde variable siteNameData.d Also not sure why you set async property to false? Please set it to true oe either remove it.

Try out this code

$.ajax(
                        {
                            url: '../Report/GetSitesofSelectedClient',
                            type: "GET",
                            cache: false,
                            datatype: "json",
                            data: { "selectedClientCode": selectedClientCode },
                            contentType: "application/json",

                            success: function(siteNameData) {

                                alert('hello');

                                $("#siteNamesDropDown").kendoDropDownList({
                                    dataTextField: "text",
                                    dataValueField: "value",
                                    template: $("#CheckboxTemplate2").html(),
                                    datasource: JSON.parse(siteNameData.d),
                                    placeholder: "Select...",
                                    select: function(e) {
                                        e.preventDefault();
                                    }
                                }).data("kendoDropDownList");

                                //PopulateSiteNamesDropDown(siteNamesReceived);
                            },
                            error: function(xhr, ajaxOptions, thrownError) {

                                ShowDialogError(xhr, 'High Chart Status Report');
                            }
                        });

1 Comment

SyntaxError: JSON.parse: unexpected character PlotHighChartReport:458 19:16:02.679 undefined. When I console.log(siteNameData) I am getting like below the first one is working for another case directly from model when rendering first time. The second one is not working 1). Object selected: true text: "Halton East" value: "AG0028" (2) siteData: "[{selected: true, "text":"Halton East", "value":"AG0028"},
0

This is My dropdownlist code. Make sure your DataText and DataValue fields are correctly mapped to the properties you are targeting.

 public JsonResult GetOpportunityListByAccount(Guid Id)
    {
        List<OpportunityViewModel> cpvm = new List<OpportunityViewModel>();            
        cpvm = GetOpportunityListByAccount(Id);            

        return Json(cpvm, JsonRequestBehavior.AllowGet);            
    }   

public List<OpportunityViewModel> GetOpportunityListByAccount(Guid Id)
    {
        List<OpportunityViewModel> oppVMList = new List<OpportunityViewModel>();
        var oppList = new OrderManager().GetOpportunitiesByAccount(Id); 

        foreach (var op in oppList)
        {
            OpportunityViewModel opvm = new OpportunityViewModel();
            opvm.OpportunityId = op.OpportunityId;
            opvm.OpportunityName = op.OpportunityName;

            oppVMList.Add(opvm);
        }

        return oppVMList;           
    }    


@(Html.Kendo().DropDownListFor(x => x.FromOpportunity)       
          .Name("OpportunityDDL")                 
          .DataTextField("OpportunityName")              
          .DataValueField("OpportunityId")                         
          .DataSource(source => {
              source.Read(read =>
               {
                   read.Action("GetOpportunityListByAccount", "CrmIntegration")
                        .Data("OnAdditionalData");
               })
                . ServerFiltering(true);
          })     
     //    .CascadeFrom("AdvertiserDDL")
          .HtmlAttributes( new { style = "margin-left:13px; width: 275px;" })
   )     

.Data is what your going to use to pass a parameter to the controller. Notice my GetOpportunityListByAccount function takes the Id as a parameter. And My "OnAdditionalData" also returns a parameter named Id. They gotta be called the same to work.

function OnAdditionalData() {        
    return {
        Id: $("#AdvertiserDDL").val()
   };
}      

Be careful if the call doesn't work it might be a data type issue. I've ran into the problem when my controller expected a Guid, using .val() which was also a guid but it didnt work. I had to change my controller to expect a string and do something like Id: "" + $("#AdvertiserDDL").val()

3 Comments

I tried the same way. But not populating the data in drop down. I am getting an array of objects which i can see in console.log. [object,Object],[object,Object},
what is .Data("OnAdditionalData"), I need to pass one parameter in to function in controller. How I can do that ?
Thanks. I tried your solution as well and was working. But I was following a different approach through out my project and Matts solution was suitable in my scenario. Thanks for the help and now understood how we can send data from view using kendo extension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.