Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • AWatters 33 posts 174 karma points
    Sep 14, 2022 @ 16:38
    AWatters
    0

    Upgrading UmbracoApiController code from U8 to U10 - ajax json returning undefined

    I am trying to update some code from U8 to U10. Essentially a UmbracoApiController and a View with a js file, where a select element is populated from a database, via a Stored Procedure.

    In the U8 version, the select box is returned with appropriate values and text but in the U10 version the value in the categories array are all "undefined" even though the Controller returns correct values to the command prompt in its Console.Write statements. It does return an array with the correct number of items though, it's just that they are undefined.

    I have tried just hardcoding data in in the Controller but it doesn't get returned via the json. I'm not sure if it's something that has changed in U10 or if I'm making a silly basic mistake somewhere.

    Here's the U8 version:

    using System;
    using System.Collections.Generic;
    using System.Web;
    using Umbraco.Web.WebApi;
    using System.Data;
    using System.Data.SqlClient;
    using Useful.Utils;
    using Umbraco.Web;
    
    public class DownloadCentreController : UmbracoApiController
    {
        public List<DropDownItem> GetCategories(int brandId)
        {
            List<DropDownItem> items = new List<DropDownItem>();
    
            SqlCommand command = DB.CreateCommand("sp_dlc_getDD");
            command.Parameters.Add("@dlc_siteNodeId", SqlDbType.Int).Value = brandId;
            SqlDataReader data = DB.ExecuteReader(command);
    
            if (data.HasRows)
            {
                while (data.Read())
                {
                    DropDownItem item = new DropDownItem();
    
                    item.value = Convert.ToInt32(data["dlc_dlcId"]);
                    item.label = Convert.ToString(data["dlc_name"]);
    
                    items.Add(item);
                }
            }
            DB.CloseReader(data);
    
            return items;
        }
    
    public class DropDownItem
        {
            public int value;
            public string label;
        }
    }
    

    downloadcentre.js

    $(document).ready(function () {
        $.ajax({
            url: '/Umbraco/Api/DownloadCentre/GetCategories',
            type: 'GET',
            dataType: 'json',
            data: { brandId: 1424 },
            contentType: 'application/json; charset=utf-8',
            success: function (categories) {
                //console.log(categories);
                //var catId = getParameterByName("prod") || 1424,
                var catId = 1424,
                    found = false;
                $('#category').empty();
                $('<option value="0">Please select</option>').appendTo('#category');
                for (var i = 0; i < categories.length; i++) {
                    var option = '<option value="' + categories[i].value + '"';
                    if (catId == categories[i].value) {
                        option += ' selected="selected"';
                        found = true;
                    }
                    option += '>' + categories[i].label + '</option>';
                    $(option).appendTo('#category');
                }
                if (found) {
                    FillProducts();
                }
            }
        });
    
    });
    

    This is the slightly modified version for U10

    using Umbraco.Cms.Web.Common;
    using Umbraco.Cms.Infrastructure.Scoping;
    using Umbraco.Cms.Web.Common.Controllers;
    using Umbraco.Cms.Core;
    using Umbraco.Cms.Core.Events;
    using Umbraco.Cms.Core.Services;
    
    public class DownloadCentreController : UmbracoApiController
    {
        private readonly IScopeProvider scopeProvider;
        private readonly UmbracoHelper _umbracoHelper;
    
        public DownloadCentreController(ILocalizedTextService localizedTextService,
            UmbracoApiControllerTypeCollection umbracoApiControllerTypeCollection,
            UmbracoHelper umbracoHelper,
            IEventAggregator eventAggregator, IScopeProvider scopeProvider)
            //: base(umbracoApiControllerTypeCollection, eventAggregator)
        {
            _umbracoHelper = umbracoHelper;
            this.scopeProvider = scopeProvider;
        }
    
    
        public List<DropDownItem> GetCategories(int brandId)
        {
            Console.Write("***---****---GetCategories: ");        
    
            List<DropDownItem> items = new List<DropDownItem>();
            using (var scope = scopeProvider.CreateScope(autoComplete: true))
            {
                var db = scope.Database;
                string strSProc = String.Format(";EXEC opc_sp_dlc_getDD @@dlc_siteNodeId={0}", brandId);
    
                List<DownloadCategory> data = db.Fetch<DownloadCategory>(strSProc);
                if (data.Any())
                {
                    Console.WriteLine("yes data");
                    int x = 1;
                    foreach (var category in data)
                    {
                        DropDownItem item = new DropDownItem();                    
                        item.value = Convert.ToInt32(category.dlc_dlcId);
                        item.value = x;
                        if (category.dlc_name is not null)
                        {
                            item.label = category.dlc_name.Trim();
                        }
                        else
                        {
                            item.label = "test";
                        }
                        Console.Write("item: ");
                        Console.Write(item.value);
                        Console.WriteLine(item.label);
                        items.Add(item);
                    }
                }
            }
            return items;
        }
    
    public class DropDownItem
        {
            public int value;
            public string label;
        }
    
        public class DownloadCategory
        {
            public int dlc_dlcId { get; set; }
            public string? dlc_name { get; set; }
        }
    }
    

    downloadcentre.js

    $(document).ready(function () {
        console.log("get categories");
        $.ajax({        
            url: '/Umbraco/Api/DownloadCentre/GetCategories',
            type: 'GET',
            dataType: 'json',
            async: true,
            data: { brandId: 1425 },
            contentType: 'application/json; charset=utf-8',
            success: function (categories) {
                console.log(categories[2].label);
                //var catId = getParameterByName("prod") || 1424,
                var found = false;
                $('#category').empty();
                $('<option value="0">Please select</option>').appendTo('#category');
                for (var i = 0; i < categories.length; i++) {
                    var option = '<option value="' + categories[i].value + '"';
                    if (catId == categories[i].value) {
                        option += ' selected="selected"';
                        found = true;
                    }
                    option += '>' + categories[i].label + '</option>';
                    $(option).appendTo('#category');
                }
                if (found) {
                    FillProducts();
                }
            }
        });
    
    });
    

    Thanks

  • AWatters 33 posts 174 karma points
    Sep 15, 2022 @ 13:57
    AWatters
    100

    Turns out the Controller needed changing:

      public class DropDownItem
        {
            public int Value { get; set; }
            public string Label { get; set; }
        }
    

    Thanks to Sebastiaan for pointing this out.

Please Sign in or register to post replies

Write your reply to:

Draft